日期:2014-05-18  浏览次数:20641 次

关于java synchronized的疑问

public class MutiThread extends Thread {

private byte[] lock = new byte[0];

private int i;

private MutiThread(int i) {
this.i = i;
}

public void run() {
synchronized (lock) {
if (i == 1)
System.out.println("A");
if (i == 2)
System.out.println("B");
if (i == 3)
System.out.println("C");
}
}

public static void main(String[] args) {
MutiThread mutiThread1 = new MutiThread(1);
mutiThread1.start();
MutiThread mutiThread2 = new MutiThread(2);
mutiThread2.start();
MutiThread mutiThread3 = new MutiThread(3);
mutiThread3.start();
}

}

我想要程序按照 A B C的顺序输出,加上了synchronized关键字也没效果。请解答~
java synchronized

------解决方案--------------------
我写了一个,用文本编辑器写的,不知道有没有错误,楼主自己运行试试。
class Printer implements Runnable{
private static Object lock=new Object();
private static int current=0;

private String content=null;
private int flag=0;

public Printer(String content,int flag){
this.content=content;
this.flag=flag;
}
public void run{
int times=0;
while(times<19){
 synchronized (lock) {
while(current%3!=flag){
try{
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(content);
times++;
Runnable.current++;
lock.notifyAll();
}
}
}

}
public class ThreadTest
{
    public static void main(String[] args)
    {
        new Thread(new Printer("A",0)).start();
new Thread(new Printer("B",1)).start();
new Thread(new Printer("C",2)).start();
    }
}