class Printer implements Runnable {
    private static Object lock = new Object();//把此处的static去掉,为什么程序就死锁了???
    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++;
                Printer.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();
    }
}

解决方案 »

  1.   

    使用static 定义的变量,多个进程共享同一个地址空间
    去掉了static ,进程间的变量互不相干
      

  2.   

    哦,原来是这样。请问以后使用对象锁,是不是都要用static呢?
      

  3.   

    锁使用的锁对象必须是同一个对象
    不一定要使用static,保证是同一个对象即可
    当然如果你用static的话,这个对象肯定就是唯一的了
      

  4.   

    synchronized(lock)中是拿lock作为对象锁进行同步
    使用static修饰lock表示,jvm在类加载的时候为lock分配内存,当声明多个Printer类的实例的时候,并不会去创建lock变量的副本,Printer类所有的实例都共享一个lock变量
    这样理解,如果lock不使用static修饰,每声明一个Printer类,都会产生一个lock实例变量,哪么这样做你的同步就没有意义了吧个人理解,不知道对不对、期待大神拍砖