数字加减
题目:设计 4 个线程对象,两个线程执行减操作,两个线程执行加操作,使其返回结果为0 1 0 1…或为0 -1 0 -1…:
public class ThreadTest {
public static void main(String[] args) {
System.out.println("开始了");
Number number = new Number();
AddThread addThread = new AddThread(number);
SubThread subThread = new SubThread(number);
new Thread(addThread, "加线程1").start();
new Thread(addThread, "加线程2").start();
new Thread(subThread, "减线程1").start();
new Thread(subThread, "减线程2").start();
}
}
class AddThread implements Runnable {
private Number num;
public AddThread(Number num) {
this.num = num;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
this.num.setAdd();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class SubThread implements Runnable {
private Number num;
public SubThread(Number num) {
this.num = num;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
this.num.setSubtract();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class Number {
private int num = 0;
private boolean flag = true;// true 可以加 false可以减
public synchronized void setAdd() throws InterruptedException {
while (!this.flag) // 这里不能使用if判断
this.wait();
Thread.sleep(100);
this.num++;
System.out.println(Thread.currentThread().getName() + "加操作,----num: " + num);
this.flag = false;
this.notifyAll();
}
public synchronized void setSubtract() throws InterruptedException {
while (this.flag) // 这里不能使用if判断
this.wait();
Thread.sleep(200);
this.num--;
System.out.println(Thread.currentThread().getName() + "减操作,减:----num: " + num);
this.flag = true;
this.notifyAll();
}
}
这里有一个坑,在阿里培训中有一个问题,如果在Number
类中增加或者减数时使用if
判断,这样如果是2个线程以上的话就会出现synchronized
锁不生效的问题
因为当一个线程在进行减操作时,有两个线程依次进入加方法中,当第一个wait()
第二个线程就可以进入,继续wait()
,当减操作结束后,notifyAll
所有线程,就会出现两个加操作的线程继续往下走,导致加二,减一的情况。
使用while函数会重新判断是否满足条件,不满足继续阻塞,就可以解决此问题