关于java多线程中的await和signalAll的使用问题

package test.synchornize;

import java.util.concurrent.locks.*;

class runab implements Runnable{
 boolean x = true;
 static Lock lock = new ReentrantLock();
 static Condition con1 = lock.newCondition();
 static Condition con2 = lock.newCondition();
 runab(boolean x){
  this.x = x;
 }
 public void run() {
  lock.lock();
  try {
   System.out.println("Start---" + Thread.currentThread().getName());
   if(x) {
    x = false;
    try {con1.await();con2.await();} catch (InterruptedException e) {}
   }
   System.out.println("End---" + Thread.currentThread().getName());
  } finally {

   con2.signalAll();
   con1.signalAll();
   lock.unlock();
  }
 }
}

public class showLock {

 public static void main(String[] args) {
  runab rab = new runab(true);
  runab rab1 = new runab(false);
  Thread th = new Thread(rab);
  Thread th1 = new Thread(rab1);
  th.start();
  try {
   Thread.sleep(100);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  th1.start();
  
 }

}

 

请问finally里面怎样写才能,让线程th继续下去呢?(即让程序最后一行输出

“End---Thread-0”)

繁花不似锦
浏览 977回答 1
1回答

胡说叔叔

呵,你这怎么写线程th都执行不下去啊,自己把自己锁死了。con1.await()和con2.await()是释放锁,线程进入阻塞状态并等待其他线程唤醒,finally根本就不会执行,那必然不会唤醒。你这con1和con2就不应该是对象内的局部变量,应该是线程间的共享变量,才能在自己等待的时候,被其他线程唤醒。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java