您当前的位置: 首页 >  Java

彭世瑜

暂无认证

  • 0浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java学习路线-16:多线程综合案例

彭世瑜 发布时间:2019-11-13 23:57:07 ,浏览量:0

第6 章 : 多线程综合案例 23 数字加减

4个线程,2个线程加,2个线程减 循环出现 加一个,减一个


// 资源
class Resource {
    private int count = 0;

    // 为false可以增加,加完了设置为true,
    // 为true可以减少,减完了设置为false
    private boolean flag = false;

    public synchronized void add() {
        if (this.flag == true) {

            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        this.count++;
        System.out.println(Thread.currentThread().getName() + " count=" + count);

        this.flag = true;
        super.notifyAll();
    }

    public synchronized void sub() {
        if (this.flag == false) {
            System.out.println(this.flag);
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        this.count--;
        System.out.println(Thread.currentThread().getName() + " count=" + count);

        this.flag = false;
        super.notifyAll();
    }
}

// 加法线程
class AddThread implements Runnable {
    private Resource resource;

    public AddThread(Resource resource) {
        this.resource = resource;
    }

    @Override
    public void run() {
        for (int i = 0; i             
关注
打赏
1665367115
查看更多评论
0.2674s