同步
我已经声明了一个类b
,它有一个在类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用户。
最佳答案
使用以下代码获得预期的答案。
b类{ //字符串消息;
public void foo(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000); // Threads go to sleeep
} catch (InterruptedException e) {
System.out.println("Caught" + e);
}
System.out.println("]");
}
}
公共(public)类 Threading 实现 Runnable {
b ob;
String msg;
Thread t;
Threading(String message, b obb) {
ob = obb;
msg = message;
t = new Thread(this); // creating a thread
t.start();
}
public void run() {
synchronized (ob) {
ob.foo(msg); // calling method of class b
}
}
public static void main(String... a) {
b obb = new b();
Threading ob = new Threading("Hello", obb); /* PASSING */
Threading ob2 = new Threading("World", obb); /* THE */
Threading ob1 = new Threading("Synch", obb);/* MESSAGE */
try {
ob.t.join();
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Caught" + e);
}
}
}
关于java - 以下代码中的同步有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19314117/