2 welen123456789 welen123456789 于 2014.03.06 09:06 提问

一个多线程分别打印abc的问题

运行这段代码,前面可以打印两三次abc,然后就卡住了,初步估计应该都进入wait了,但是不明白为什么,求指导`public class TestDemo {

public static void main(String[] args) {
    final Locker p = new Locker();
    Task11 a = new Task11(p);
    Task21 b = new Task21(p);
    Task31 c = new Task31(p);
    Thread one = new Thread(a);
    one.start();
    Thread two = new Thread(b);
    two.start();
    Thread three = new Thread(c);
    three.start();
}

}

class Task11 implements Runnable {

private Locker obj;
public Task11(Locker p){
    this.obj = p;
}

@Override
public void run() {
    for(int i = 0; i < 5; i++){
        synchronized (obj) {
            if(obj.num != 0){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println("a");
                obj.num = 1;
                obj.notifyAll();
            }
        }
    }
}

}
class Task21 implements Runnable {

private Locker obj;
public Task21(Locker p){
    this.obj = p;
}

@Override
public void run() {
    for(int i = 0; i < 5; i++){
        synchronized (obj) {
            if(obj.num != 1){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println("b");
                obj.num = 2;
                obj.notifyAll();
            }
        }
    }
}

}
class Task31 implements Runnable {

private Locker obj;
public Task31(Locker p){
    this.obj = p;
}

@Override
public void run() {
    for(int i = 0; i < 5; i++){
        synchronized (obj) {
            if(obj.num != 2){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println("c");
                obj.num = 0;
                obj.notifyAll();
            }
        }
    }
}

}

class Locker {
int num = 0;
}`

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!