java多线程六:多线程案例分析-数字加减

文章出处 https://www.jianshu.com/p/6bc888b82008

文章对应视频出处:https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

设计4个线程对象,2个线程执行减操作,2个线程执行加操作。

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Resource res = new Resource();
        SubThread st = new SubThread(res);
        AddThread at = new AddThread(res);
        new Thread(at, "A ").start();
        new Thread(at, "B ").start();
        new Thread(st, "X ").start();
        new Thread(st, "Y ").start();
    }
}
class AddThread implements Runnable {
    private Resource resource;
    public AddThread(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                this.resource.add();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class SubThread implements Runnable {
    private Resource resource;
    public SubThread(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                this.resource.sub();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Resource {//定义一个操作的资源
    private int num = 0;//这个是要进行加减操作的数据
    private boolean flag = true;//加减的切换
    //flag = true:表示可以进行加法操作,但是无法进行减法操作
    //flag = false:表示可以进行减法操作,但是无法进行加法操作
    public synchronized void add() throws InterruptedException {//执行加法操作
        while (flag == false) {//现在需要执行的是减法操作,加法操作要等待
            System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】进行等待");
            super.wait();
            System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】被释放");
        }
        Thread.sleep(100);
        this.num++;
        System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】num = " + this.num);
        this.flag = false;//加法操作执行完毕,需要执行减法操作
        super.notifyAll();//唤醒全部等待线程

    }
    public synchronized void sub() throws InterruptedException {//执行减法操作
        while (flag == true) { //减法操作需要等待,注意:一定要用while 详见:文章多线程六关于while详解
            System.out.println("【减法操作 -" + Thread.currentThread().getName() + "】进行等待");
            super.wait();
        }
        Thread.sleep(200);
        this.num--;
        System.out.println("【减法操作 -" + Thread.currentThread().getName() + "】num = " + this.num);
        this.flag = true;
        super.notifyAll();
    }
}

  这是一个经典的多线程开发操作,这个程序中一定要考虑的核心本质在于:加一个、减一个,整体的计算结果应该在0、1(或-1) 中循环出现才是合理的。 

加减方法中while判断说明:

正确例子

【加法操作 -加法线程-A-】进行等待
【加法操作 -加法线程-B-】被释放
【加法操作 -加法线程-B-】进行等待(while继续判断)

错误例子
【加法操作 -加法线程-A-】进行等待
【加法操作 -加法线程-B-】被释放
【加法操作 -加法线程-B-】num = -46(if直接走了)

发布了52 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/YKWNDY/article/details/104850228