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

锁对象的小问题

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();
    }
}

------解决方案--------------------
使用static 定义的变量,多个进程共享同一个地址空间
去掉了static ,进程间的变量互不相干
------解决方案--------------------
引用:
哦,原来是这样。请问以后使用对象锁,是不是都要用static呢?

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