-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
问题
一个线程同时启动,依次打印A,B,C,D
求解
使用wait和notifyAll实现
package com.beatifulCoding;
public class ProducerAndConsumer {
static volatile int step = 1;
static Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread A = new Thread(()->{
synchronized (lock){
System.out.println("A");
step = 2;
lock.notifyAll();
}
});
Thread B = new Thread(()->{
synchronized (lock){
while (step!=2){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
step = 3;
lock.notifyAll();
}
});
Thread C = new Thread(()->{
synchronized (lock){
while (step!=3) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
step = 4;
lock.notifyAll();
}
});
Thread D = new Thread(()->{
synchronized (lock){
while (step!=4){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("D");
lock.notifyAll();
}
});
A.start();
B.start();
C.start();
D.start();
Thread.sleep(1000);
}
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels