class ThreadOne{
private Object LOCK = new Object();
private int num;
public static void main(String[] args) {
ThreadOne a = new ThreadOne();
new Thread(()->{
try {
a.printNum(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "1").start();
new Thread(()->{
try {
a.printNum(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "2").start();
new Thread(()->{
try {
a.printNum(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "3").start();
new Thread(()->{
try {
a.printNum(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "4").start();
}
public void printNum(int num) throws InterruptedException {
synchronized (LOCK){
while(num%4!=0){
LOCK.wait();
}
num++;
System.out.println(Thread.currentThread().getName());
LOCK.notifyAll();
}
}
}
在这里插入图片描述