【发布时间】:2013-11-26 07:07:44
【问题描述】:
我尝试了一些代码来证明同步块锁定机制的可靠性。考虑我的示例代码
我的时钟对象。
public class MyLock {
final static Object lock=new Object();
}
具有同步块的类
public class Sample {
public void a(String input) {
System.out.println(input+" method a");
synchronized (lock) {
System.out.println("inside synchronized block in a");
try {
System.out.println("waiting in a");
Thread.sleep(5000);
System.out.println("calling b() from a");
new Sample().b("call from a");
System.out.println("waiting again in a");
Thread.sleep(5000);
System.out.println("Running again a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void b(String input) {
System.out.println(input+" method b");
synchronized (lock) {
System.out.println("bbb " + input);
}
}
}
Test1 类
public class Test1 implements Runnable{
public static void main(String[] args) {
new Thread(new Test1()).start();
new Thread(new Test2()).start();
}
@Override
public void run() {
new Sample().a("call from main");
}
}
Test2 类
public class Test2 implements Runnable {
@Override
public void run() {
new Sample().b("call from main");
}
}
我这样做是因为我认为如果持有锁的同一个线程要访问另一个使用同一个锁锁定的方法,就会出现死锁情况。现在考虑输出
call from main method a
call from main method b
inside synchronized block in a
waiting in a
calling b() from a // i thought this will cause a dead lock
call from a method b
bbb call from a
waiting again in a
Running again a
bbb call from main
现在您可以看到没有这样的问题。我的问题是Java 如何处理这种情况?
【问题讨论】:
标签: java multithreading synchronized