首页 新闻 会员 周边

JAVA多线程 问题

0
[待解决问题]

package com.zehui.thread.commonexamples;

/**

  • @Classname Test
  • @Description TODO
  • @Date 2020/3/20 1:35
  • @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();
        }
    }
}

}

以上为代码,为什么设置等待唤醒,还是会有连续减,连续加的情况,明明是先加后减的

长臂猿爱跳伞的主页 长臂猿爱跳伞 | 菜鸟二级 | 园豆:402
提问于:2020-03-20 03:11

知道为什么了,直接把判断语句改成while就行了,真的sb

钟大泽 4年前
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册