class ThreadRunnable implements Runnable{
synchronized public void run(){
System.out.println("In Runnable implemented class");
try {
Thread.sleep(60000);
System.out.println("sleeping over");
System.out.println(System.currentTimeMillis());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Sample {
public static void main(String [] args){
ThreadRunnable tr = new ThreadRunnable();
Thread t1 = new Thread(tr);
Thread t2 = new Thread(new ThreadRunnable());
t1.start();
t2.start();
}
}
由于其同步方法,t2 线程应该在 t1 之后打印 SOP,但是两个线程同时打印 SOP。谁能告诉我为什么?
最佳答案
synchronized
方法隐式同步 this
。在您的情况下,ThreadRunnable
的实例。
但是每个线程都有自己的实例,因此它们使用两个不同的监视器。
您有多种选择来解决您的问题,例如:
- 使用
private static final Object lock = new Object();
作为具有同步块(synchronized block)的监视器。 - 或更简单地说
Thread t2 = new Thread(tr);
关于java - 同步块(synchronized block)中的 sleep() 方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46808789/