Search⌘ K
AI Features

Basic Thread Handling

Explore the fundamental techniques for handling threads in Java concurrency. Understand how to use thread joining to wait for completion, distinguish daemon threads from user threads, apply thread sleeping without misusing it for synchronization, and interrupt threads to handle unresponsive behavior. This lesson prepares you to control thread life cycles effectively in multithreaded applications.

Joining Threads

A thread is always created by another thread except for the main application thread. Study the following code snippet. The innerThread is created by the thread which executes the main method. You may wonder what happens to the innerThread if the main thread finishes execution before the innerThread is done?

Java
class Demonstration {
public static void main( String args[] ) throws InterruptedException {
ExecuteMe executeMe = new ExecuteMe();
Thread innerThread = new Thread(executeMe);
innerThread.setDaemon(true);
innerThread.start();
}
}
class ExecuteMe implements Runnable {
public void run() {
while (true) {
System.out.println("Say Hello over and over again.");
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
// swallow interrupted exception
}
}
}
}

If you execute the above code, you’ll see no output. That is because the main thread exits right after starting the innerThread. Once it exits, the JVM also kills the spawned thread. On line 6 we ...