第6 章 : 多线程综合案例
23 数字加减
4个线程,2个线程加,2个线程减 循环出现 加一个,减一个
// 资源
class Resource {
private int count = 0;
// 为false可以增加,加完了设置为true,
// 为true可以减少,减完了设置为false
private boolean flag = false;
public synchronized void add() {
if (this.flag == true) {
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.count++;
System.out.println(Thread.currentThread().getName() + " count=" + count);
this.flag = true;
super.notifyAll();
}
public synchronized void sub() {
if (this.flag == false) {
System.out.println(this.flag);
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.count--;
System.out.println(Thread.currentThread().getName() + " count=" + count);
this.flag = false;
super.notifyAll();
}
}
// 加法线程
class AddThread implements Runnable {
private Resource resource;
public AddThread(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i
关注
打赏