同步
我已经声明了一个class b
具有同步方法的方法,该方法可以在以下位置访问class c
:
class b {
String msg;
public synchronized void foo() {
System.out.print("[" + msg);
try {
Thread.sleep(1000); // Threads go to sleeep
} catch (InterruptedException e) {
System.out.println("Caught" + e);
}
System.out.println("]");
}
}
class a implements Runnable {
b ob;
Thread t;
a(String msg, b obb) {
ob = obb;
ob.msg = msg;
t = new Thread(this); // creating a thread
t.start();
}
public void run() {
ob.foo(); // calling method of class b
}
public static void main(String... a) {
b obb = new b();
a ob = new a("Hello", obb); /* PASSING */
a ob1 = new a("Synch", obb); /* THE */
a ob2 = new a("World", obb);/* MESSAGE */
try {
ob.t.join();
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Caught" + e);
}
}
}
我期待输出:
[Hello]
[Synch]
[World]
但是代码给出了:
[World]
[World]
[World]
帮我提些建议。我是一个天真的 JAVA 用户。