- /*
- 死锁。
- */
- class DeadLockDemo implements Runnable
- {
- static Object chopsticks = new Object();
- static Object knifeAndFork = new Object();
- private boolean flag;
- DeadLockDemo(boolean flag){
- this.flag = flag;
- }
- public void run(){
- if(flag){
- while(true){
- try{
- Thread.sleep(1000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- synchronized(chopsticks){
-
- System.out.println(Thread.currentThread().getName()
- + "---- if ---- chopsticks");
- synchronized(knifeAndFork){
- System.out.println(Thread.currentThread().getName()
- + "---- if ---- knifeAndFork");
- }
- }
- }
- }else{
- while(true){
- try{
- Thread.sleep(1000);
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- synchronized(knifeAndFork){
-
- System.out.println(Thread.currentThread().getName()
- + "---- else ---- knifeAndFork");
- //continue;
- /**/synchronized(chopsticks){
- System.out.println(Thread.currentThread().getName()
- + "---- else ---- chopsticks");
- }
- }
- }
- }
- }
- }
复制代码 |
|