死锁:同步中嵌套同步,有关死锁代码是毕老师交代必须会自己写的代码
- package com.itheima;
- class Deadlock implements Runnable
- {
- private boolean flag ;
-
- Deadlock(boolean flag)
- {
- this.flag = flag;
- }
-
- @Override
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized (DeadlockT.locka)
- {
- System.out.println("if locha");
- synchronized (DeadlockT.lockb)
- {
- System.out.println("if lockb");
- }
- }
- }
-
- }else
- {
- while(true)
- {
- synchronized (DeadlockT.lockb)
- {
- System.out.println("else lockb");
- synchronized (DeadlockT.locka)
- {
- System.out.println("else locka");
- }
-
- }
- }
-
- }
- }
- }
- class DeadlockT
- {
- static Object locka = new Object();
- static Object lockb = new Object();
- }
- class DeadlockTest
- {
- public static void main(String[] args)
- {
- Thread t1 = new Thread(new Deadlock(true));
- Thread t2 = new Thread(new Deadlock(false));
- t1.start();
- t2.start();
- }
- }
复制代码 |
|