JUC---06线程间通信

Posted jenne-blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JUC---06线程间通信相关的知识,希望对你有一定的参考价值。

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

  要使多线程之间按顺序调用,实现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() + "	 " + total + "	");

            //通知
            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() + "	 " + total + "	");

            //通知
            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() + "	 " + total + "	");

            //通知
            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线程间通信的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程:线程间通信方式

Java多线程:线程间通信方式

多线程-线程间的通信

多线程-线程间的通信

多线程_线程间通信

c++ 线程间通信方式