使用Lock实现线程的顺序执行(精准唤醒)

使用Lock实现线程的顺序执行(精准唤醒),第1张

使用Lock实现线程的顺序执行(精准唤醒)


package com.learn;


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

public class Thread_Execute_Order {


   public static void main(String[] args) {

      Resource resource = new Resource();

      new Thread(() -> {
         try {
            //很重要,让其它依赖线程先执行wait方法。可以自己去掉试一下
            Thread.sleep(100);
         } catch (Exception e) {
            e.printStackTrace();
         }
         for(int i=0;i <5 ;i++){
            resource.method1();
         }
      },"ThreadA").start();

      new Thread(() -> {
         for(int i=0;i <5 ;i++){
            resource.method2();
         }
      },"ThreadB").start();

      new Thread(() -> {
         for(int i=0;i <5 ;i++){
            resource.method3();
      }},"ThreadC").start();



   }


}

class Resource{

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

   private boolean methodBeginFlag = false;

   public void method1(){
      lock.lock();
      try {
         if(!methodBeginFlag ){
            //无条件限制性method1
            methodBeginFlag = true ;
         }else{
            condition1.await();
         }
         System.out.println("------------------->执行method1");
         Thread.sleep(1*1000);
         condition2.signal();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         lock.unlock();
      }

   }

   public void method2(){
      lock.lock();
      try {
         condition2.await();
         System.out.println("------------------->执行method2");
            Thread.sleep(1*1000);
         condition3.signal();

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


   public void method3(){
      lock.lock();
      try {
         condition3.await();
         System.out.println("------------------->执行method3");
         Thread.sleep(1*1000);
         condition1.signal();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         lock.unlock();
      }
   }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5636720.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存