public class ThreadTest2 {
public static void main(String[] args) {
Sample sample = new Sample();
IncreaseThread thread1 = new IncreaseThread(sample);
DecreaseThread thread2 = new DecreaseThread(sample);
thread1.start();
thread2.start();
}
}
class Sample {
private int number;
// 增加
public synchronized void increase() {
if (number != 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number++;
notify();
System.out.println(" increase = " + number);
}
// 减少
public synchronized void decrease() {
if (number == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
number--;
notify();
System.out.println(" decrease = " + number);
}
}
class IncreaseThread extends Thread {
private Sample sample;
public IncreaseThread(Sample sample) {
this.sample = sample;
}
public void run() {
super.run();
while (true)
sample.increase();
}
}
class DecreaseThread extends Thread {
private Sample sample;
public DecreaseThread(Sample sample) {
this.sample = sample;
}
public void run() {
super.run();
while (true)
sample.decrease();
}
}
两个线程的情况下这段代码能实现number 加-减-的的效果,number 的实现始终是0和一
如果开四个线程,两个加、两个减,以上代码就无法实现
Sample sample = new Sample();
IncreaseThread thread1 = new IncreaseThread(sample);
IncreaseThread thread2 = new IncreaseThread(sample);
DecreaseThread thread3 = new DecreaseThread(sample);
DecreaseThread thread4 = new DecreaseThread(sample);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
原因分析:1和2线程负责增加,3、4负责减小,假如3线程先进入decrease方法,这个时候nubmer==0,条件为true,3线程等待(wait),由于wait具有释放锁的功能,其他线程这个时候都可以访问该对象synchronized 方法,假如4线程也进入decrease方法,number还是为零,这个时候3、4线程都处于等待状态。假如1线程进入increase,判断number的值,number为零,条件为假,执行number++,number值变成一并且打印值,再执行notify,由于3、4线程都处于等待状态,不知道会notify哪个线程,假如唤醒3号线程,执行number--,number值变成零,再notify,由于4线程还是wait状态,假如4线程被唤醒,执行number--,这个时候number就变成了-1,由于这一步错了后面肯定接着错。
具体解决办法,期待各位网友给出答案,我把if改成while,也没用
java Object类的wait和notify学习
最新推荐文章于 2019-04-22 21:10:33 发布