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条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler