线程间定制化通信---按顺序执行线程

Posted weixin_ancenhw

tags:

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

启动三个线程:
AA线程打印5次,BB打印6次,CC打印3次

  //定义标记
    private int flag = 1;

    private Lock lock = new ReentrantLock();

    //定义锁状态
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void loopThread()
        lock.lock();
        try 
            while (flag!=1)
                c1.wait();
            
            for (int i = 0; i < 5; i++) 
                System.out.println(Thread.currentThread()+"执行次数:"+i);
            
            flag=2;
            c2.signal();
         catch (InterruptedException e) 
            e.printStackTrace();
        finally 
            lock.unlock();
        
    

    public void loopThread2()
        lock.lock();
        try 
            while (flag!=2)
                c2.wait();
            
            for (int i = 0; i < 6; i++) 
                System.out.println(Thread.currentThread()+"执行次数:"+i);
            
            flag=3;
            c3.signal();
         catch (InterruptedException e) 
            e.printStackTrace();
        finally 
            lock.unlock();
        
    

    public void loopThread3()
        lock.lock();
        try 
            while (flag!=3)
                c3.wait();
            
            for (int i = 0; i < 3; i++) 
                System.out.println(Thread.currentThread()+"执行次数:"+i);
            

         catch (InterruptedException e) 
            e.printStackTrace();
        finally 
            lock.unlock();
        
    



    @Test
    public void contextLoads() 
        new Thread(()->
            loopThread();
        ,"AA").start();

        new Thread(()->
            loopThread2();
        ,"BB").start();

        new Thread(()->
            loopThread3();
        ,"CC").start();
    

以上是关于线程间定制化通信---按顺序执行线程的主要内容,如果未能解决你的问题,请参考以下文章

JUC---06线程间通信

JUC---06线程间通信

4_线程间定制化通信

07-SV线程以及线程间的通信

shell多线程之进程间通信

Java并发编程(04):线程间通信,等待/通知机制