锁定采购订单?

时间:2014-04-02 16:15:09

标签: java multithreading

我试图理解多线程的一个例子:

class Callme {
    void call(String msg) {
        System.out.print(msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
}

class Caller implements Runnable {
    String msg;
    Callme target;

    void call(String msg) {
        System.out.println(msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
    }

    public Caller(Callme target, String msg) {
        this.target = target;
        this.msg = msg;
        new Thread(this).start();
    }

    public void run() {
        synchronized (target) {
            target.call(msg);
        }
    }
}

public class Main {
    public static void main(String args[]) {
        Callme target = new Callme();
        new Caller(target, "1");
        new Caller(target, "2");
        new Caller(target, "3");
        new Caller(target, "4");
    }
}

输出为1432。为什么不是1234?锁定获取的顺序是什么"目标"?我认为它应该像这样工作:

  1. 第一个"来电者"对象锁定" target"对象 - 打印" 1"并且睡眠1秒(阻止其他线程执行target.call(msg))
  2. 首先睡眠1次"来电"释放锁定然后下一个(第二个?)"来电者"对象锁定" target"对象 - 打印" 2"并且睡1s
  3. 等等。我的思维错误在哪里?

1 个答案:

答案 0 :(得分:1)

这里要注意的是,synchronized不保证执行顺序。它保证的是,在synchronized完成之前,任何其他线程都不会修改被锁定的对象。

无法保证在多线程中将采用锁序列。

可能存在这样的情况,线程1在进入synchronized块之前就已被击中/睡眠。

相关问题