Java - How to create, run, and stop a Thread

Let`s see how to create, run, and stop a Thread in Java.

Thread creation and execution

You can create and run a Thread like this:

Thread thread = new Thread();
thread.start();

The above code simply creates a thread.

If you want to make some code work, you need to inherit Thread and implement it.

If you inherit Thread and override run() as follows, run() is called when the Thread is executed.

public class MyThread extends Thread {

    public MyThread() {
    }

    @Override
    public void run() {
        log("Thread is running");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log("Finish run()");
    }
}

You can run the Thread implemented above as follows:

MyThread thread = new MyThread();
log("Start thread");
thread.start();

Output:

19:25:13.418 (main) Start thread
19:25:13.419 (Thread-0) Thread is running
19:25:16.419 (Thread-0) Finish run()

For reference, log() is a log method that outputs the time and thread name together as shown below.

public static void log(String msg) {
    System.out.println(LocalTime.now() + " ("
            + Thread.currentThread().getName() + ") " +  msg);
}

Thread, Runnable

Instead of inheriting and implementing Thread, there is also a way to pass an object implementing Runnable to the Thread and execute it.

You can implement Runnable like this:

public static class MyThreadRunnable implements Runnable {

    private final AtomicBoolean running = new AtomicBoolean(false);

    public MyThreadRunnable() {
    }

    @Override
    public void run() {
        log("Thread is running");
        log("Do something");
    }
}

And if you pass Runnable as an argument to Thread as shown below, run() implemented in Runnable is executed when the thread is executed.

MyThreadRunnable runnable = new MyThreadRunnable();
Thread thread = new Thread(runnable);

log("Start thread");
thread.start();

Output:

19:28:57.276 (main) Start thread
19:28:57.277 (Thread-0) Thread is running
19:28:57.277 (Thread-0) Do something

Join

Sometimes the main thread waits for other threads to finish their work. In this case, you can use join().

In the example below, when join() is called, the thread is blocked and waits until all tasks of the thread are completed. When the operation is complete, join() returns and executes the next code.

MyThread thread = new MyThread();
log("Start thread");
thread.start();

thread.join();
log("Everything is done");

Join, set timeout

join() can also wait indefinitely if the Thread does not terminate. You can set a Timeout so that it doesn`t wait any longer after a certain amount of time.

Timeout can be set by passing the time as an argument like join(miliseconds).

MyThread thread = new MyThread();
log("Start thread");
thread.start();

thread.join(1000);
log("Everything is done");

If you look at the result, you can see that if the thread doesn`t finish within 1 second, it does the next code without waiting

22:08:41.365 (main) Start thread
22:08:41.366 (Thread-0) Thread is running
22:08:42.366 (main) Everything is done
22:08:44.366 (Thread-0) Finish run()

End Thread

Thread.stop() does not safely terminate a thread and is no longer supported.(deprecated)

Instead, it should be implemented to terminate a thread using a flag method or to terminate a thread using an Interrupt method.

Terminate the thread by flag method

I implemented Runnable as follows. This class has an object called running. We will use this to mean running or terminating a thread by turning on and off.

public static class MyThreadRunnable implements Runnable {

    private final AtomicBoolean running = new AtomicBoolean(false);

    public MyThreadRunnable() {
    }

    public void stop() {
        log("Stop this thread");
        running.set(false);
    }

    public void run() {
        running.set(true);
        while (running.get()) {
            try {
                log("Thread is running");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Thread was interrupted");
            }
        }
    }
}

Thread was created and executed as follows. After 5 seconds, call runnable.stop() to change running to false so that run() ends.

MyThreadRunnable runnable = new MyThreadRunnable();
Thread thread = new Thread(runnable);
thread.start();

Thread.sleep(5000);

log("Send stop signal");
runnable.stop();

Output:

19:39:13.038 (Thread-0) Thread is running
19:39:14.039 (Thread-0) Thread is running
19:39:15.039 (Thread-0) Thread is running
19:39:16.039 (Thread-0) Thread is running
19:39:17.039 (Thread-0) Thread is running
19:39:17.946 (main) Send stop signal
19:39:17.946 (main) Stop this thread

Since the thread is also terminated when run() is finished, it can be implemented like this.

Terminate the thread with Interrupt method

This time, I implemented Runnable as follows. There is no runnable flag, and when executed, it runs indefinitely.

public static class MyThreadRunnable implements Runnable {
    public MyThreadRunnable() {
    }

    public void run() {
        while (true) {
            try {
                log("Thread is running");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log("Thread was interrupted.");
                log("Release some resources");
                log("Done");
                return;
            }
        }
    }
}

I ran the thread like this: And after 5 seconds, it called interrupt().

Thread thread = new Thread(new MyThreadRunnable());
thread.start();

Thread.sleep(5000);

log("isInterrupted(): " + thread.isInterrupted());

log("Interrupt this thread");
thread.interrupt();

log("isInterrupted(): " + thread.isInterrupted());

When interrupt() is called, an InterruptedException is thrown in the running code of the thread. All you have to do is clean up the resource and make it shut down when this exception is thrown.

  • interrupt(): Raise an Interrupt exception
  • isInterrupted(): Returns a boolean if the status is Interrupted or not.

Output:

19:46:10.010 (Thread-0) Thread is running
19:46:11.010 (Thread-0) Thread is running
19:46:12.011 (Thread-0) Thread is running
19:46:13.011 (Thread-0) Thread is running
19:46:14.011 (Thread-0) Thread is running
19:46:14.946 (main) isInterrupted(): false
19:46:14.946 (main) Interrupt this thread
19:46:14.946 (main) isInterrupted(): true
19:46:14.946 (Thread-0) Thread was interrupted.
19:46:14.946 (Thread-0) Release some resources
19:46:14.946 (Thread-0) Done
codechachaCopyright ©2019 codechacha