I'm reading Java The Complete Reference(9th Edition) after year of fooling around with Java. Been happy with the book so far but I now have a really strange problem with synchronized threads:
package syncro;
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller1 implements Runnable {
String msg;
Callme target;
Thread t;
public Caller1(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
@Override
public void run() {
synchronized (target) { // SYNC BLOCK
target.call(msg);
}
}
}
public class Syncronized {
public static void main(String[] args) {
Callme target = new Callme();
Caller1 ob1 = new Caller1(target, "Hello");
Caller1 ob2 = new Caller1(target, "Synchronized");
Caller1 ob3 = new Caller1(target, "World");
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
}
It prints out:
[Hello]
[World]
[Synchronized]
and I don't understand how that's even possible. Also worth mentioning, if I swap the lines
Caller1 ob2 = new Caller1(target, "Synchronized");
Caller1 ob3 = new Caller1(target, "World");
(constructor is called with the string "World" before "Synchronized") it will print
[Hello]
[Synchronized]
[World]
as I would have expected in the first place.
I didn't find a question like this here so I hope I'm doing this right... Thanks!
java.lang.concurrentthat were designed for this purpose, eg.CountDownLatch.