日期:2014-05-20  浏览次数:20699 次

一个多线程分别打印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;
}

------解决方案--------------------
你理解下

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;