当前位置: 代码迷 >> J2SE >> Java 线程 同步代码块内代码没执行(无死锁)(附源码)解决方案
  详细解决方案

Java 线程 同步代码块内代码没执行(无死锁)(附源码)解决方案

热度:504   发布时间:2016-04-24 02:04:52.0
Java 线程 同步代码块内代码没执行(无死锁)(附源码)
public class NotifyTest {

/**

* @param args

*/

public static Object lock;

public NotifyTest(){
NotifyTest.lock = new Object();
}

public static void main(String[] args) {

// TODO Auto-generated method stub

NotifyTest testNotify = new NotifyTest();

  ThreadB b = testNotify.new ThreadB();

  b.start();

  System.out.println("b is start");
  synchronized(NotifyTest.lock){

  try{
  NotifyTest.lock.wait(); // 暂时放弃对象锁,让主线程暂停,让ThreadB开始执行
 
  System.out.println("Waiting for b to complete");
  System.out.println("testPoint");
  }

  catch(Exception e){

  e.printStackTrace();

  }

  System.out.println("Final Total is:"+b.total);

  }

}

class ThreadB extends Thread{


int total;

public void run()

{

synchronized(NotifyTest.lock)

{

System.out.println("ThreadB is running");

for(int i=0;i<100;i++)

{

total+=i;

}
System.out.println("testPoint1");
NotifyTest.lock.notify(); // 执行完毕,唤醒被暂停的线程

}

}

}

}


------解决方案--------------------
其实是因为每次b先执行,都notify了,然后才wait,再也没线程去唤醒了~~~
可以在ThreadB的run方法前面加上:
Java code
try {    Thread.sleep(1000);    } catch (InterruptedException e) {}
  相关解决方案