...

/

Basic Thread Handling

Basic Thread Handling

This lesson shows various thread handling methods with examples.

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?

Press + to interact
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 ...