package com.zehui.thread.commonexamples;
/**
@Created by Nikla
*/
public class NumCalculateTest {
public static void main(String[] args) {
Resources resources = new Resources();
AddThread addThread = new AddThread(resources);
SubThread subThread = new SubThread(resources);
new Thread(addThread, "加法线程 A").start();
new Thread(addThread, "加法线程 B").start();
new Thread(subThread, "减法线程 X").start();
new Thread(subThread, "减法线程 Y").start();
}
}
class Resources {
//结果
private volatile int num = 0;
private boolean flag = true;//操作标志
// true 可以执行加法操作,false 执行减法操作
public synchronized void addMethod() throws InterruptedException {
if (this.flag == false) {
super.wait();
}
Thread.sleep(100);
this.num++;
System.out.println(Thread.currentThread().getName() + "执行了加法操作 num= " + num);
this.flag = false;
this.notifyAll();
}
public synchronized void subMethod() throws InterruptedException {
if (this.flag == true) {
super.wait();
}
Thread.sleep(200);
this.num--;
System.out.println(Thread.currentThread().getName() + "执行了减法操作 num= " + num);
this.flag = true;
this.notifyAll();
}
}
class AddThread implements Runnable {
private Resources resources;
public AddThread(Resources resources) {
this.resources = resources;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
this.resources.addMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable {
private Resources resources;
public SubThread(Resources resources) {
this.resources = resources;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
this.resources.subMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
以上为代码,为什么设置等待唤醒,还是会有连续减,连续加的情况,明明是先加后减的
知道为什么了,直接把判断语句改成while就行了,真的sb
– 钟大泽 4年前