java并发编程学习之Condition用法一

35次阅读

共计 1121 个字符,预计需要花费 3 分钟才能阅读完成。

Condition


主要用 await 和 signal,跟 Object 的 wait、notify 差不多用法,只是这里是用 lock 来替换 synchronized。
这边复制一下之前的 wait 和 notif 例子修改一下

示例

public class ConditionDemo {Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    private String tv = "广告";

    static class Tv extends Thread {
        ConditionDemo waitDemo;

        public Tv(ConditionDemo waitDemo) {this.waitDemo = waitDemo;}

        @Override
        public void run() {waitDemo.waitTv();
        }
    }

    public void waitTv() {lock.lock();
        try {while (tv.equals("广告")) {
                try {condition.await();
                    if (tv.equals("广告")) {System.out.println(Thread.currentThread().getName() + "-" + "骗人,还是广告");
                    }
                } catch (InterruptedException e) {e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "-" + "愉快的追剧");
        }finally {lock.unlock();
        }
    }

    public void sendTrueMsg() {lock.lock();
        try {
            tv = "正剧";
            condition.signalAll();}finally {lock.unlock();
        }
    }

    public void sendFalseMsg() {lock.lock();
        try {condition.signalAll();
        }finally {lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {ConditionDemo waitDemo = new ConditionDemo();
        Tv tv1 = new Tv(waitDemo);
        Tv tv2 = new Tv(waitDemo);
        tv1.start();
        tv2.start();
        Thread.sleep(100);
        waitDemo.sendFalseMsg();
        Thread.sleep(100);
        waitDemo.sendTrueMsg();}
}

运行结果如下:

正文完
 0