【发布时间】:2017-10-16 18:39:03
【问题描述】:
我创建了一个简单的 Worker:
public class Worker {
public synchronized void writeData() {
try {
System.out.println("write Data , thread id = " + Thread.currentThread().getId());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void readData() {
try {
System.out.println("readData , thread id = " + Thread.currentThread().getId());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
AFAIK,如果多个线程访问同一个 Worker 实例,synchronized 只会阻塞访问同一方法的线程。 AKA 如果线程 A 调用 writeData 而 B 使用 readData,它们不会相互影响(如果我错了,请纠正我)。
但是,当我尝试通过以下代码进行演示时:
private static void testWithThreads() {
final Worker worker = new Worker();
new Thread(() -> {
System.out.println("start read thread");
for (int i = 0; i < 20; i++) {
worker.readData();
}
}).start();
new Thread(() -> {
System.out.println("start write thread");
for (int i = 0; i < 20; i++) {
worker.writeData();
}
}).start();
}
我得到了这样的输出(注意我们这里有Thread.sleep 2 秒):
start read thread
readData , thread id = 10
start write thread
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
write Data , thread id = 11
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
readData , thread id = 10
谁能给我解释一下?他们似乎以某种方式相互屏蔽了。
【问题讨论】:
-
synchronized方法在您调用方法的实例上同步。所以在这种情况下它们是在同一个对象上同步的,这两种方法肯定会互相阻塞。 -
Thread.currentthread.join()是自死锁。当前线程等待自己永远“死”......
标签: java multithreading