如何检查 Java 中的 sleep() 方法是否持有锁?
How to check whether sleep() method in Java holds lock or not?
class MyThread extends Thread{
public void run(){
print();
}
synchronized public void print() {
// for(int i = 0; i< )
System.out.println("Thread : " + Thread.currentThread().getName());
try{
Thread.sleep(5000);}
catch(InterruptedException e ){
}
}
}
public class MyClass {
public static void main(String args[]) throws InterruptedException {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("A");
t2.setName("B");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("EOM");
}
}
程序的输出 -
ThreadA
ThreadB
立即打印两行
5 秒后
EOM
According to my understanding, one of the thread should go in print() and acquire lock and only releases it after 5 seconds but here both the threads executed immediately and then "EOM" got printed after 5 seconds.
synchronized
在一个实例方法中,各个实例互不干扰
如果该方法是 static
那么它将在实例之间共享。
您写道:
synchronized public void print() {
...
}
这只是一种short-cut的写法:
public void print() {
synchronized(this) {
...
}
}
您的两个线程中的每一个都在 MyClass
class 的不同实例上运行,因此,您的两个线程中的每一个都在 不同的对象上同步(不同的 this
参考)。
当您使用 synchronized(o)
块时,这只会阻止两个不同的线程同时在 同一对象 o
上同步。
class MyThread extends Thread{
public void run(){
print();
}
synchronized public void print() {
// for(int i = 0; i< )
System.out.println("Thread : " + Thread.currentThread().getName());
try{
Thread.sleep(5000);}
catch(InterruptedException e ){
}
}
}
public class MyClass {
public static void main(String args[]) throws InterruptedException {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("A");
t2.setName("B");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("EOM");
}
}
程序的输出 -
ThreadA
ThreadB
立即打印两行 5 秒后
EOM
According to my understanding, one of the thread should go in print() and acquire lock and only releases it after 5 seconds but here both the threads executed immediately and then "EOM" got printed after 5 seconds.
synchronized
在一个实例方法中,各个实例互不干扰
如果该方法是 static
那么它将在实例之间共享。
您写道:
synchronized public void print() {
...
}
这只是一种short-cut的写法:
public void print() {
synchronized(this) {
...
}
}
您的两个线程中的每一个都在 MyClass
class 的不同实例上运行,因此,您的两个线程中的每一个都在 不同的对象上同步(不同的 this
参考)。
当您使用 synchronized(o)
块时,这只会阻止两个不同的线程同时在 同一对象 o
上同步。