- class Deadlocked implements Runnable{
- boolean flag;
- Deadlocked(boolean flag)
- {
- this.flag=flag;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- if(flag)
- {
- synchronized(Lock.DEADLOCKA)
- {
- try{Thread.sleep(10);}catch(InterruptedException e){}
- System.out.println("if locka");
- synchronized(Lock.DEADLOCKB)
- {
-
- System.out.println("else lockb");
- }
- }
- }
- else
- {
- synchronized(Lock.DEADLOCKB)
- {
- try{Thread.sleep(10);}catch(InterruptedException e){}
- System.out.println("if lockb");
- synchronized(Lock.DEADLOCKA)
- {
- System.out.println("else locka");
- }
- }
- }
- }
-
-
- }
- class Lock{
- public static final Lock DEADLOCKA=new Lock();
- public static final Lock DEADLOCKB=new Lock();
- }
- public class ThreadTest5_Deadlocked {
- public static void main(String [] args)
- {
- Deadlocked d1=new Deadlocked(true);
- Deadlocked d2=new Deadlocked(false);
- Thread t1=new Thread(d1);
- Thread t2=new Thread(d2);
- t1.start();
- t2.start();
- }
- }
复制代码
一个死锁的小程序,比如两人一人只有一只筷子,有饭,都想吃饭 但是必须得要一双筷子,然后两个人谁也不给谁自己手里的那只 所以都吃不上。这个过程比作是死锁吧 。也有和谐的时候就是一方妥协的 |