class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
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();
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
System.out.println("rahul");
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
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");
}
}
}
在这个节目时,我使用的是System.out.print不同步的块(“拉胡”),它完美的打印输出,但是当我把SOP的这些不必要的声明(“拉胡”)输出被扭曲为什么会发生,而不是同步?