我有一个带有synchronized块的shout()方法。
private void shout(){
System.out.println("SHOUT " + Thread.currentThread().getName());
synchronized(this){
System.out.println("Synchronized Shout" + Thread.currentThread().getName());
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Synchronized Shout" + Thread.currentThread().getName());
}
}如果我有两个线程运行这个方法,我假设两个“同步的喊叫”总是一个接一个出现,对吗?在"Synchronized Shout“之间不能有其他语句?
发布于 2010-05-03 12:17:25
因为打印“呼喊...”的那行不需要锁,它可以出现在任何地方。因此,即使一个线程持有锁,另一个线程也可能进入并打印"SHOUT...“。
下面的代码显示了交错:
public class Interleave {
public static void main(String[] args) throws Throwable {
Task task = new Task();
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
Thread.sleep(25);
t2.start();
}
private static class Task implements Runnable {
public void run() {
shout();
}
private void shout() {
System.out.println("SHOUT " + Thread.currentThread().getName());
synchronized (this) {
System.out.println("Synchronized Shout " + Thread.currentThread().getName());
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Synchronized Shout " + Thread.currentThread().getName());
}
}
}
}它会打印出来
SHOUT Thread-0
Synchronized Shout Thread-0
SHOUT Thread-1
Synchronized Shout Thread-0
Synchronized Shout Thread-1
Synchronized Shout Thread-1https://stackoverflow.com/questions/2755969
复制相似问题