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) {}