我正在学习编写更好的多线程程序,线程安全和确定性。我遇到了这段代码
// File Name : Callme.java
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
// File Name : Caller.java
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
// File Name : Synch.java
public class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
产生以下输出(尝试了〜100次)
[Hello]
[World]
[Synchronized]
所以我的第一个问题是,这个输出是否有保证?我还观察到,如果我将睡眠更改为100
它仍然会产生相同的输出,但是如果我将睡眠10
更改为输出更改为
[Hello]
[Synchronized]
[World]
第二个问题是,如果有保证,为什么?最后但并非最不重要的,为什么这个输出?我希望它是
[Hello]
[Synchronized]
[World]