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
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
Please disable your ad blocker and refresh the window to use this website.