fxhu09 2014-05-27 11:26
浏览 274
已采纳

线程死锁问题

以下程序为了学习而写
两个线程依次按序打印从1到100,一个只打印奇数,另一个只打印偶数。但是经常发生死锁,请问为什么
public class Test16 implements Runnable{

private int turn;
private int num;
private int sum;
static Integer counter=0;
public Test16(int turn,int num,int sum){
    this.turn=turn;
    this.num=num;
    this.sum=sum;
}
public  synchronized void run() {
    while(counter<sum){
        while(turn!=counter%num){
            try {
                wait();
            } catch (InterruptedException e) {
                                    e.printStackTrace();
            }
        }

            counter++;
            System.out.print(counter+" "); 
            notifyAll();


    }

}

public static void main(String[] args){
    new Thread(new Test16(0,2,100)).start();
     new Thread(new Test16(1,2,100)).start();
}

}

  • 写回答

5条回答 默认 最新

  • guazixing 2014-05-27 13:00
    关注

    问题在public synchronized void run() { 相当于 synchronized(this),而 main中
    new Thread(new Test16(0,2,100)).start();
    new Thread(new Test16(1,2,100)).start();
    这样是2个不同的test16对象,因而是2个不同的锁,2个锁都在等待自己的资源(2个线程都停止了),所以不可能被唤醒。其实楼主想锁定的是共享的counter,counter的是static的,属于类对象,所以要在类上加锁才行。
    代码修改如下:
    [code="java"]
    public void run() {
    synchronized (Test16.class) {
    while (counter < sum) {
    while (turn != counter % num) {
    try {
    Test16.class.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

                counter++;
                System.out.println(counter + "   turn : " + turn);
                Test16.class.notifyAll();
    
            }
        }
    
    }
    

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?