首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

关于线程死锁解决办法

2012-04-30 
关于线程死锁Java codepublic class Test11 extends Thread {public static void main(String[] args) {Te

关于线程死锁

Java code
public class Test11 extends Thread {    public static void main(String[] args) {        Test11 t = new Test11();        t.start();//t线程开始执行        try {            Thread.sleep(500);//让主线程等待0.5秒,此时t线程应该执行结束        } catch (InterruptedException e) {            e.printStackTrace();        }        synchronized (t) {            try {                System.out.println("wait for t to complete...");                t.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("total:" + t.total);        }    }    int total;    public void run() {        synchronized (this) {//运行期间保持锁            for (int i = 0; i < 100; i++) {                total += i;            }            System.out.println(total);            notify();//唤醒等待此对象锁的一个线程        }    }}


1.启动子线程t,t.start()运行它
2.让主线程等待0.5秒,在这0.5秒内,t线程已经运行完毕
3.进入主线程中的synchronzed块中,t.wait()放弃t对象锁,等待被唤醒
4.但是此时t线程已经执行完毕,不会再唤醒了,然后就死锁了?

这段代码运行会发生死锁的状态,但是这种情况可能会经常出现,该如何避免呢?

[解决办法]
随便怎么处理一下都不会死锁.
比如:
Java code
      synchronized (t) {            try {                 if(t.total==0)     //加仪判断,如果条件成立,说明就等待,否则不等待了。                   {                     System.out.println("wait for t to complete...");                     t.wait();                   }            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("total:" + t.total);        } 

热点排行