死锁

创建时间:2015/8/23 16:19
更新时间:2015/8/23 16:19

package com.text.thread1;


class Resource{
       String name;
       Resource(String name){
               this.name =name;
              
       }
}

class MyThread implements Runnable{
       
       String name;
       Resource r1;
       Resource r2;
       
       MyThread(Resource r1,Resource r2,String nm){
              
               this.r1 =r1;
               this.r2 =r2;
               name=nm;
       }
       
        public void run() {
               synchronized (r1 ) {
                     System. out.println(this .name +"获得" +r1 .name );
                      try {
                           Thread. sleep(1000);
                     } catch (InterruptedException e) {
                            // TODO 自动生成的 catch 块
                           e.printStackTrace();
                     }
              System. out.println(this .name +"等待" +r2 .name );
              }
               synchronized (r2 ) {
                      try {
                           Thread. sleep(1000);
                     } catch (InterruptedException e) {
                            // TODO 自动生成的 catch 块
                           e.printStackTrace();
                     }
              }
              
              
       }
       
}

public class Deadlock {

        public static void main(String[] args) {

              Resource r1= new Resource("资源1" );
              Resource r2= new Resource("资源2" );
              Resource r3= new Resource("资源3" );
              MyThread m1= new MyThread(r1, r2, "线程1" );
              MyThread m2= new MyThread(r2, r3, "线程2" );
              MyThread m3= new MyThread(r3, r1, "线程3" );
              Thread t1= new Thread(m1);
              Thread t2= new Thread(m2);
              Thread t3= new Thread(m3);
              t1.start();
              t2.start();
              t3.start();
              
       }
       
       

}