public class Thread_A {Sortie
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++;
//libérer le thread A
notify();
}
}
});
Thread_B.start();
synchronized (Thread_B) {
try {
System.out.println("Thread A est bloqué - En attente de thread B"+
"qu'il termine");
//mettre en attente le thread A
Thread_B.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("le thread B a terminé - Le thread A est relaché");
}
}
}
Thread A est bloqué En attente de thread B qu'il termine
le thread B a terminé. Le thread A est relaché
public class Sleep {Sortie
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: J'ai dormis pendant 4 secondes");
} 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 somme = 0;
for(int i = 0 ; i < 50; i++)
somme +=i;
System.out.println("Thread B: j'ai terminé");
}
}
}
Thread ALe processus A a commencé avant le processus B mais le B a fait le traitement pendant que le A était endormi et a terminé le premier.
Thread B
Thread B: j'ai terminé
Thread A: J'ai dormis pendant 4 secondes
Please disable your ad blocker and refresh the window to use this website.