我有两个 Java 类,如下...
(1) JavaClass SyncTest:它定义一个类(实现 Runnable)并调用 SyncTestCalled 类中定义的“同步”方法(名为“call”)
(2) JavaClass SyncTestCalled :有一个同步方法。
------
After calling from main(), I am thinking it should output something like:
[Two]
[Three]
[One]
But, it outputs something like this (note the open bracket which is not paired in right locations) :
[[[Two]
Three]
One]
代码有什么问题吗?请帮忙。非常感谢!
<小时/> Here is the code of these two classes...
public class SyncTest implements Runnable {
Thread t;
String name;
SyncTestCalled syncTestCalled;
public SyncTest(String name) {
t = new Thread(this, name);
syncTestCalled = new SyncTestCalled();
this.name = name;
t.start();
}
public void run() {
syncTestCalled.call(this.name);
}
public static void main(String[] args) {
SyncTest syncTest1 = new SyncTest("One");
SyncTest syncTest2 = new SyncTest("Two");
SyncTest syncTest3 = new SyncTest("Three");
}
} // of class SyncTest
public class SyncTestCalled {
public SyncTestCalled() {
// Do nothing
}
synchronized public void call(String message) {
System.out.print("[");
try {
Thread.sleep(1000);
System.out.print(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("]");
}
} // of class SyncTestCalled
最佳答案
当您使用 synchronized
作为方法声明的一部分时,Java 会尝试获取调用该方法的对象的监视器(锁)。所以像
synchronized public void call(String message) {
...
}
相当于
public void call(String message) {
synchronized (this) {
...
}
}
在代码中,您创建三个不同的 SyncTestCalled
对象,并将每个单独的对象传递给不同的 SyncTest
实例。换句话说,没有什么是协调的。每次调用
syncTestCalled.call(this.name);
在不同的对象上同步,因此没有线程需要等待其他线程。
这取决于线程调度程序首先到达哪里,所以你会得到类似的输出
[[[Two]
Three]
One]
或
[[[OneThree]
Two]
]
<小时/>
请注意,Thread.sleep(long)
不会放弃线程当前拥有的任何监视器。
关于java - 为什么在这个例子中使用synchronized(Java并发)是不正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21083301/