【发布时间】:2018-04-26 13:59:35
【问题描述】:
所以当我注意到程序中显示的空同步块导致输出同步时,我只是在搞乱基本并发。块里什么都没有,为什么会这样呢?
public class MainClass {
public static void main(String[] args) throws InterruptedException {
SyncTest f = new SyncTest();
f.start();
for (int i = 0; i < 20; i++) {
System.out.println("MAIN THREAD:" + i);
Thread.sleep(500);
synchronized (f) {
for (int t = 0; t < 15; t++) {
Thread.sleep(100);
}
}
}
}
}
class SyncTest extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("OTHER THREAD: " + i);
Thread.sleep(1300);
synchronized (this) {} //Why does this have an effect on the output when commented?
} catch (InterruptedException ex) {}
}
}
}
【问题讨论】:
-
synchronized命令的目的是在线程之间进行同步。为什么你会认为它没有任何效果,只是因为它不包含任何代码? -
你是什么意思
causes the outputs to sync up -
自己复制并粘贴代码,您可以看到输出有块存在和没有块时会发生什么。
标签: java concurrency synchronization output synchronized