I'm learning to write better multi-threaded programs, thread-safe and deterministic. I came across this piece of code
// 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");
}
}
}
which produces the following output(tried it ~100 times)
[Hello]
[World]
[Synchronized]
So my first question is, is this output guaranteed? I also observed that if I change sleep to 100
it still produces the same output, but if I change sleep to 10
the output changes to
[Hello]
[Synchronized]
[World]
Second question is, If it's guaranteed, why? Last but not the least, Why this output? I expected it to be
[Hello]
[Synchronized]
[World]
Runnable
target is wrong. The new thread can start executing therun()
method before the constructor has finished initializing the object. The more general expression of this rule is never make an object visible to another thread before its constructor has returned.