public class Work5 {
public static void main(String[] args) {
Date date = new Date();
new Thread(()->{
for (int i = 0; i < 10; i++) {
date.add();
}
},"加线程1").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
date.add();
}
},"加线程2").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
date.reduce();
}
},"减线程1").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
date.reduce();
}
},"减线程2").start();
}
}
class Date{
private int j = 0;
public synchronized void add() {
while (j == 1) {
try {
// 等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
j++;
System.out.println(Thread.currentThread().getName() + "=>" + j);
// 通知其他线程
this.notifyAll();
}
public synchronized void reduce() {
while (j == 0) {
try {
// 等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
j--;
System.out.println(Thread.currentThread().getName() + "=>" + j);
// 通知其他线程
this.notifyAll();
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交