pilgrimage_yy 2013-09-10 10:08
浏览 215
已采纳

求多线程调度问题调试

目标是建立三个线程 th1,th2,th3,希望其能按照顺序th1->th2->th3的顺序执行。

下面贴出我的代码,运行时总是不能得到正确的结果,求大神指点~~~~

package threadSeq;

public class testThSeq {

    public volatile static int state = 1;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread th1 = new Thread(new Runnable() {
            public void run() {
                try {
                    increaseAndNotifyAll(1);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });

        Thread th2 = new Thread(new Runnable() {
            public void run() {
                try {
                    increaseAndNotifyAll(2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });
        Thread th3 = new Thread(new Runnable() {
            public void run() {
                try {
                    increaseAndNotifyAll(3);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        th3.start();
        th2.start();
        th1.start();
    }

    public synchronized static void increaseAndNotifyAll(int wantedState) throws InterruptedException {
        System.out.println("state:"+state+";"+Thread.currentThread()+wantedState);
        while(state!=wantedState){
            Thread.currentThread().wait();
            Thread.currentThread().notifyAll();
        }
        System.out.println(Thread.currentThread() + " finished");
        state++;
    }
}
  • 写回答

1条回答 默认 最新

  • dsm02955299 2013-09-10 11:03
    关注

    有两个问题。
    第一:获取哪个对象的锁。都只能对那个对象wait和notify。你现在通过synchronized获得的是testThSeq.class的锁。(synchronized一个方法,获取的是方法所属对象的锁,synchronized一个static方法,获取的是方法所属类的class的锁)所以你不能Thread.currentThread().wait();应该testThSeq.class.wait()。notifyAll也一样。

    第二:notifyAll紧跟着wait后面,并且都在条件判断state!=wantedState里面,必将产生死锁。线程要么state!=wantedState为true,进入wait等待。要么state!=wantedState为false。永远无法执行到notifyAll这条语句。
    改为:

    [code="java"]
    while (state != wantedState) {
    testThSeq.class.wait();
    }
    testThSeq.class.notifyAll();
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问