java併發編程學習之Condition-用法(一)

Condition

clipboard.png
主要用await和signal,跟Object的wait、notify差很少用法,只是這裏是用lock來替換synchronized。
這邊複製一下以前的wait和notif例子修改一下segmentfault

示例

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();
    }
}

運行結果以下:ide

clipboard.png

相關文章
相關標籤/搜索