/*
以下代码想实现的得是对同个变量进行 交替 加减操作。
*
/
public class NumAddSub {
public static void main(String[] args) {
Cul cul = new Cul();
AddThread addThread = new AddThread(cul);
SubThread subThread = new SubThread(cul);
new Thread(addThread, "add A").start();
new Thread(addThread, "add B").start();
new Thread(subThread, "sub X").start();
new Thread(subThread, "sub Y").start();
}
}
class AddThread implements Runnable {
private Cul cul;
public AddThread(Cul cul) {
this.cul = cul;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
this.cul.add();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class SubThread implements Runnable {
private Cul cul;
public SubThread(Cul cul) {
this.cul = cul;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
this.cul.sub();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Cul {
private int num = 0;
private boolean flag = true; // true为可以执行add,false为执行sub
public synchronized void add() throws Exception {
if (!this.flag) {
super.wait();
}
Thread.sleep(10);
this.num++;
System.out.println(Thread.currentThread().getName() + " 【add】 num = " + num);
this.flag = false;
super.notifyAll();
}
public synchronized void sub() throws Exception {
if (this.flag) {
super.wait();
}
Thread.sleep(20);
this.num--;
System.out.println(Thread.currentThread().getName() + " 【sub】 num = " + num);
this.flag = true;
super.notifyAll();
}
}
原本正常执行,但是都后来就发生了问题
但都实现了同步方法
不清楚为何会发生
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。