- public class TestDeathlock {
- /**
- * @param args
- */
- public static void main(String[] args) {
- DeathLock dl1 = new DeathLock(true);
- DeathLock dl2 = new DeathLock(false);
- Thread thread1 = new Thread(dl1);
- Thread thread2 = new Thread(dl2);
- thread1.start();
- thread2.start();
- }
- }
- class DeathLock implements Runnable{
- private boolean b ;
- DeathLock(Boolean b){
- this.b = b;
- }
- static Object o1=new Object();
- static Object o2=new Object();
-
- @Override
- public void run() {
- if(b){
- synchronized (o1) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- synchronized (o2) {
- System.out.println("这里是b为true的");
- }
- }
- if(!b){
- synchronized (o2) {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- synchronized (o1) {
- System.out.println("这里是b为false的");
- }
-
- }
- }
-
- }
复制代码 两句都能打印,是怎么回事呢? |