一个简单的死锁例子

一个简单的死锁例子,希望对大家有用。、

写法一:

 public class DeadLock{
 static private Object o1="123";
 static private Object o2="234";
 public static void main(String[] args){
  Thread t1 = new Thread1(o1,o2);
  Thread t2 = new Thread2(o1,o2);
   t1.start();
  t2.start();
 }
}
class Thread1 extends Thread{
 Object o1;
 Object o2;
 public Thread1(Object o1,Object o2){
  this.o1=o1;
  this.o2=o2;
 }
 public void run(){
  synchronized(o1){
   System.out.println("线程一1");
   try{
    sleep(2000);
   }catch(Exception e){
    System.out.println("出错1");
   }
   synchronized(o2){
    System.out.println("线程一2");
   }
  }
 }
}
class Thread2 extends Thread{
 Object o1;
 Object o2;
 public Thread2(Object o1,Object o2){
  this.o1=o1;
  this.o2=o2;
 }
 public void run(){
  synchronized(o2){
   System.out.println("线程二1");
   try{
    sleep(2000);
   }catch(Exception e){
    System.out.println("出错2");
   }
   synchronized(o1){
    System.out.println("线程二2");
   }
  }
 }

 

写法二:

public class Deadlock {

    public static void main(String args[]) {
        final Object o1 = "asd";
        final Object o2 = "qwe";
        Thread t1 = new Thread() { 

            public void run() {
                synchronized (o1) {
                    System.out.println("Thread 1: locked o1");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                         System.out.println("error");
                    }
                    synchronized (o2) {
                        System.out.println("Thread1: locked o2");
                    }
                }
            }
        };

        Thread t2 = new Thread() {        
            public void run() {
                synchronized (o2) {
                    System.out.println("Thread2: locked o2");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                         System.out.println("error");
                    }
                    synchronized (o1) {
                        System.out.println("Thread2: locked o1");
                    }
                }
            }
        };

        t1.start();
        t2.start();
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值