当前位置:   article > 正文

多线程,顺序执行(方法一)_c语言多线程的运行顺序

c语言多线程的运行顺序

public class SortThread {
 private Lock lock;
 private Condition conditionA;
 private Condition conditionB;
 public SortThread(Lock lock, Condition conditionA, Condition conditionB) {
  super();
  this.lock = lock;
  this.conditionA = conditionA;
  this.conditionB = conditionB;
 }
 private class ThreadA extends Thread{
  @Override
  public void run() {
   super.run();
   while(true){
    lock.lock();
    System.out.println("ThreadA--run");
    try {
     conditionB.signal();//唤醒B
     TimeUnit.SECONDS.sleep(1);
     conditionA.await();//使当前线程处于Waiting状态
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
  
 }
 private class ThreadB extends Thread{
  @Override
  public void run() {
   while(true){
    lock.lock();
    System.out.println("ThreadB--run");
    try {
     conditionA.signal();//唤醒A
     TimeUnit.SECONDS.sleep(1);
     conditionB.await();//使当前线程处于Waiting状态
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 }
 public static void main(String[] args) {
  Lock lock = new ReentrantLock();
  Condition conditionA = lock.newCondition();
  Condition conditionB = lock.newCondition();
  SortThread st = new SortThread(lock,conditionA,conditionB);
  ThreadA ta = st.new ThreadA();
  ThreadB tb = st.new ThreadB();
  ta.start();
  tb.start();
  
 }
}

注意:一定要先执行signal(),若先执行了await(),程序会直接挂起,即直接进入waiting状态,不会继续往下执行。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/197834
推荐阅读
相关标签
  

闽ICP备14008679号