多线程之间通讯例子

原创
2016/08/18 22:51
阅读数 156
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.hb.thread.lock.Business.*;

/**
 * 多线程之间的通讯
 */
public class ThreeConditionLock {
    public static void main(String[] arg) {
        Business bus = new Business();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 4; i++) {
                    bus.sub1(i);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i < 4; i++) {
                    bus.sub2(i);
                }
            }
        }).start();

        for (int i = 1; i < 4; i++) {
            bus.sub3(i);
        }
    }
}

class Business {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    private int count = 1;

    public void sub1(int i) {
        lock.lock();
        try {
            while (count != 1) {
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 1; j < 5; j++) {
                System.out.println("No.1 Thread ,当前序列 : " + j + "第" + i + "循环");
            }
            count++;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void sub2(int i) {
        lock.lock();
        try {
            while (count != 2) {
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 1; j < 5; j++) {
                System.out.println("No.2 Thread ,当前序列 : " + j + "第" + i + "循环");
            }
            count++;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void sub3(int i) {
        lock.lock();
        try {
            while (count != 3) {
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            for (int j = 1; j < 5; j++) {
                System.out.println("No.3 Thread ,当前序列 : " + j + "第" + i + "循环");
            }
            count = 1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部