线程通信方式:condition+lock实现线程之间的通信方式

/*
 * 线程质之间的通信方式二:condition+lock实现线程之间的通信方式
 * */
public class ThreadCommunication2 {

    private int i = 0;

    /*重入锁:参数: true 代表公平锁 ,false:独占锁*/
    private Lock lock = new ReentrantLock(false);

    private Condition condition = lock.newCondition();

    /*奇数*/
    public void odd() {
        while (i < 10) {
            try {
                lock.lock();
                if (i % 2 == 1) {
                    /*唤醒该线程*/
                    condition.signal();
                    System.out.println("奇数:" + i+","+Thread.currentThread().getName());
                    i++;
                } else {
                    try {
                        /*该线程等待*/
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }

    /*偶数*/
    public void even() {
        while (i < 10) {
            lock.lock();
            try {
                if (i % 2 == 0) {
                    System.out.println("偶数:" + i +","+Thread.currentThread().getName());
                    i++;
                    /*唤醒该线程*/
                    condition.signal();
                } else {
                    try {
                        /*该线程等待*/
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }

        }
    }

    public static void main(String[] args) {
        ThreadCommunication2 threadCommunication = new ThreadCommunication2();
        Thread thread1 = new Thread("thread1") {
            @Override
            public void run() {
                threadCommunication.odd();
            }
        };
        Thread thread2 = new Thread("thread2") {
            @Override
            public void run() {
                threadCommunication.even();
            }
        };

        thread1.start();
        thread2.start();
    }
}

运行结果:

偶数:0,thread2
奇数:1,thread1
偶数:2,thread2
奇数:3,thread1
偶数:4,thread2
奇数:5,thread1
偶数:6,thread2
奇数:7,thread1
偶数:8,thread2
奇数:9,thread1

 


版权声明:本文为zhaoliubao1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。