WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Intermediate · question 34 of 100

What is a thread in Java? How would you create and start a thread?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, a thread is a lightweight process that runs concurrently with other threads within a program. A program that uses threads can perform multiple tasks simultaneously, improving performance and responsiveness.

To create a thread in Java, there are two basic approaches:

Implementing the Runnable interface and passing an instance of it to a Thread constructor. Subclassing the Thread class and overriding the run() method.

Here’s an example of how to create a thread using the first approach:

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Hello from a thread!");
    }
}

// create a new thread
Thread thread = new Thread(new MyRunnable());

// start the thread
thread.start();

In this example, we define a class MyRunnable that implements the Runnable interface and overrides its run() method. We then create a new Thread object and pass an instance of MyRunnable to its constructor. Finally, we start the thread by calling its start() method.

Here’s an example of how to create a thread using the second approach:

class MyThread extends Thread {
    public void run() {
        System.out.println("Hello from a thread!");
    }
}

// create a new thread
MyThread thread = new MyThread();

// start the thread
thread.start();

In this example, we define a class MyThread that subclasses the Thread class and overrides its run() method. We then create a new instance of MyThread and start it by calling its start() method.

Both approaches are valid ways to create a thread in Java, but using the Runnable interface is generally preferred because it allows more flexibility in implementing thread behavior.

To summarize, a thread in Java is a lightweight process that runs concurrently with other threads within a program. To create a thread, you can either implement the Runnable interface and pass an instance of it to a Thread constructor, or subclass the Thread class and override its run() method. Once created, a thread can be started by calling its start() method.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics