三个线程顺序打印ADC 10次

synchronized实现,悲观锁的体现

public class Test2 {

    public static void main(String[] args) throws InterruptedException {
        //锁对象,是线程竞争的资源
        NumResource res = new NumResource(0);
        //创建三个线程,参数:根据资源res的变化,判断count条件是否满足,来输出结果ch
        TestThread t1 = new TestThread(0, res, "A");
        TestThread t2 = new TestThread(1, res, "B");
        TestThread t3 = new TestThread(2, res, "C");

        //启动三个线程,无关顺序
        t2.start();
        t3.start();
        t1.start();
    }


}

//线程类
class TestThread extends Thread {

    //参数:根据锁资源res的变化,判断count条件是否满足,来输出结果ch
    private int count;
    private NumResource res;
    private String ch;

    public TestThread(int count, NumResource res, String ch) {
        this.count = count;
        this.res = res;
        this.ch = ch;
    }

    @Override
    public void run() {
        // 每个线程循环抢夺资源锁
        while (res.num < 10) {
            synchronized (res) {
                //System.out.println(res.num);
                //抢到锁就判断,是否满足条件输出结果
                if (res.num % 3 == count) {
                    System.out.println(ch + " " + Thread.currentThread().getName());
                    //对锁资源内容作更改
                    res.num++;
                    //激活一个线程,被激活的线程会从res.wait()语句下-行开始执行,并再一次尝试抢夺资源锁,没有抢到就被卡到synchronized (res)处
                    res.notifyAll();
                }
                try {
                    // 暂停当前抢到res资源锁的线程
                    res.wait();
                    //每个线程的结束条件,每个线程被唤醒后,会判断是否满足条件来进行推出
                    //若满足,则表示当前线程要终止,并再一次调用res.notifyAll()来激活一个线程,因为其他的线程都被卡到了res.wait(); 处,他们没法得到执行并判断自己是否要结束
                    if (res.num >= 10) {
                        res.notifyAll();
                        //跳出while循环,放弃抢夺资源的权力
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//锁资源
class NumResource {
    //num的更改会判断当前线程是否有结果输出
    int num;

    public NumResource(int num) {
        this.num = num;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章