读书人

Java 线程 同步代码块内代码没执行(无

发布时间: 2012-02-22 19:36:54 作者: rapoo

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

读书人网 >J2SE开发

热点推荐