Java threads - Difference between sleep, wait, and notify
Both methods sleep() and wait() pause the current thread and resume its execution path after a notification that is triggered after a certain amount of time or by another process.wait can be woken up by another thread that calls the notify. It is important that wait et notify be called in a block synchronized which is used for mutual exclusion. The Method notify wakes up the first process that triggered the wait.
Example of wait() and notify()
In this program, process B runs inside process A and creates a mutual exclusion zone to block and prevent process A from executing the statement after the block try/catch.public class Thread_A {Output
public static void main(String[] args) {
Thread Thread_B = new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
int i=0;
while(i< 100)
i++;
//free thread A
notify();
}
}
});
Thread_B.start();
synchronized(Thread_B) {
try {
System.out.println("Thread A is blocked - Waiting for thread B"+
"to complete");
//put the A
Thread_B.wait() on hold;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread B has completed - Thread A is released");
}
}
}
Thread A is stuck Waiting for thread B to complete
Thread B has finished. Thread A is released
Example of sleep()
The sleep() locks a process and executes it for a set amount of time. This method is used for synchronization with time (e.g. wake up after 4 seconds) or to say sleep and let other threads run.
public class Sleep {Output
public static void main(String[] args) {
ThreadA a = new ThreadA();
a.start();
ThreadB b = new ThreadB();
b.start();
}
static class ThreadA extends Thread{
@Override
public void run() {
try {
System.out.println("Thread A");
sleep(4000);
System.out.println("Thread A: I slept for 4 seconds");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static class ThreadB extends Thread{
@Override
public void run() {
System.out.println("Thread B");
int sum = 0;
for(int i = 0 ; i < 50; i++)
sum +=i;
System.out.println("Thread B: I'm done");
}
}
}
Thread AProcess A started before process B but B did the processing while process A was asleep and finished the first
Thread B
Thread B: I finished
Thread A: I slept for 4 seconds