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();
作为带有同步块的监视器。Thread t2 = new Thread(tr);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句