英文:
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");
}
}
Output of the Program -
ThreadA
ThreadB
*Immediately prints both lines*
*After 5 seconds*
EOM
>> According to my understanding, one of the threads should go into the print() and acquire lock, and only releases it after 5 seconds. However, here both threads executed immediately, and then "EOM" got printed after 5 seconds.
英文:
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");
}
}
Output of the Program -
ThreadA
ThreadB
Immediately prints both line
After 5 seconds
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.
答案1
得分: 2
synchronized
在实例方法中使用时,每个实例彼此之间不会干扰。
如果这个方法是 static
的,那么它将在不同实例之间共享。
英文:
The synchronized
is in an instance method, and each instance doesn't interfere with each other.
If the method were static
then it would be shared between the instances.
答案2
得分: 0
你写的代码是:
synchronized public void print() {
...
}
这只是一种简写方式,等价于:
public void print() {
synchronized(this) {
...
}
}
你的两个线程分别在不同的MyClass
类实例上操作,因此,你的两个线程分别在不同的对象(不同的this
引用)上进行同步。
当你使用synchronized(o)
块时,这只会阻止两个不同的线程同时在相同的对象o
上进行同步。
英文:
You wrote:
synchronized public void print() {
...
}
That's just a short-cut way of writing:
public void print() {
synchronized(this) {
...
}
}
Each of your two threads is operating on a different instance of your MyClass
class, therefore, each of your two threads is synchronizing on a different object (different this
reference).
When you use synchronized(o)
blocks, that only prevents two different threads from synchronizing on the same object o
at the same time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论