Threads in Java

Overview

When a program is executing it follows a path, that is Thread. Threads are used to perform critical tasks in the background without interrupting the main thread.

There are two ways to create a Thread.
  • By extending the class Thread
  • By implementing an interface Runnable

Five states of Thread

  1. Born
  2. Runnable
  3. Running
  4. Non Runnable
  5. Dead

sleep() vs wait()

  • sleep() belongs to Thread class whereas wait() belongs to an object.
  • sleep() can be called without a synchronized context but wait() should be called in a synchronized context.
  • sleep() does not release lock on an object but wait() releases lock on an object during synchronization.
  • sleep() is a static method but wait() is not a static method.
  • sleep() is executed on a Thread but wait() method is executed on an object. 

interrupt()

  • This method is used to interrupt an executing Thread.
  • If a Thread is in sleep() or wait() state then the interrupt() method will get called and the catch() statement gets executed. If a Thread doesn't go in sleep() or wait() state then the interrupt() method won't affect the execution of the Thread.
Example of interrupt()
 public class InterruptThreadMain extends Thread {
@Override
public void run() {
super.run();
try {
for (int i = 0; i < 10; i++) {
System.out.println(currentThread() + " " + i);
Thread.sleep(3000);
}
} catch (Exception e) {
System.out.println(currentThread() + " throws the exception: " + e.getMessage());
}
}

public static void main(String[] args) {
InterruptThreadMain interruptThreadMain = new InterruptThreadMain();
interruptThreadMain.start();
interruptThreadMain.interrupt();

Thread anonymousThread = new Thread(() -> {
try {
for (int j = 0; j < 10; j++) {
System.out.println(currentThread() + " " + j);
// Thread.sleep(2000);
}
} catch (Exception e) {
e.printStackTrace();
}
});
anonymousThread.start();
anonymousThread.interrupt();
}
}
 Thread[Thread-0,5,main] 0
Thread[Thread-1,5,main] 0
Thread[Thread-1,5,main] 1
Thread[Thread-1,5,main] 2
Thread[Thread-1,5,main] 3
Thread[Thread-1,5,main] 4
Thread[Thread-1,5,main] 5
Thread[Thread-1,5,main] 6
Thread[Thread-1,5,main] 7
Thread[Thread-1,5,main] 8
Thread[Thread-1,5,main] 9
Thread[Thread-0,5,main] throws the exception: sleep interrupted

Do's and Dont's 

  1. You cannot start a thread again. If you do you will get a runtime exception IllegalThreadStateException

Reference



Comments