码迷,mamicode.com
首页 > 编程语言 > 详细

JUC---06线程间通信(二)

时间:2020-05-06 20:03:21      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:red   通过   signal   cond   style   实例   nal   cep   system   

二、线程间定制化调用通信

  要使多线程之间按顺序调用,实现A->B->C按顺序输出,使用Lock锁实现,通过Lock锁创建三个Condition实例(三把钥匙),通过不同的条件,调用不同钥匙的awite()跟singnal()方法,阻塞或唤醒其他线程

  代码实现:

package com.jenne.mydemo;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData {

    private int num = 1;//1:AA,2:BB,3:CC

    private Lock lock = new ReentrantLock();
    Condition cd1 = lock.newCondition();
    Condition cd2 = lock.newCondition();
    Condition cd3 = lock.newCondition();

    public void print5(int total) {
        lock.lock();
        try {
            //判断
            while (num != 1) {
                cd1.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + "\t " + total + "\t");

            //通知
            num = 2;
            cd2.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void print10(int total) {
        lock.lock();
        try {
            //判断
            while (num != 2) {
                cd2.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + "\t " + total + "\t");

            //通知
            num = 3;
            cd3.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void print15(int total) {
        lock.lock();
        try {
            //判断
            while (num != 3) {
                cd3.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + "\t " + total + "\t");

            //通知
            num = 1;
            cd1.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class TestThreadOrderAccess {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                shareData.print5(i);
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                shareData.print10(i);
            }
        }, "BB").start();
new Thread(() -> { for (int i = 1; i <= 10; i++) { shareData.print15(i); } }, "CC").start(); } }

 

JUC---06线程间通信(二)

标签:red   通过   signal   cond   style   实例   nal   cep   system   

原文地址:https://www.cnblogs.com/jenne-blog/p/12838229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!