码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程_死锁的例子

时间:2017-08-13 13:28:17      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:out   roi   gbk   tac   aaa   div   int   abs   and   

 

/*说明:零长度的byte数组对象创建起来将比任何对象都经济,查看编译后的字节码:
生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码。*/

public class DeadLock 
{    
    public static void main(String[] args) 
    {
        byte[] lock1 = new byte[0];
        byte[] lock2 = new byte[0];

        Thread th1=new Thread(new Processer1(lock1,lock2));
        Thread th2=new Thread(new Processer2(lock1,lock2));
        th1.setName("th1");
        th2.setName("th2");

        th1.start();
        th2.start();
    }
}

class Processer1 implements Runnable
{
    private byte[] lock1;
    private byte[] lock2;
    Processer1(byte[] lock1,byte[] lock2){
        this.lock1=lock1;
        this.lock2=lock2;
    }

    public void run(){
        synchronized(lock1){
            System.out.println(Thread.currentThread().getName()+" get lock1,and is waiting for lock2.");
            try{
                Thread.sleep(5000);
            }catch(InterruptedException e){
                    e.printStackTrace();
            }

            synchronized(lock2){
                System.out.println(Thread.currentThread().getName()+" has get lock2.");
            }
        }
    }
}

class Processer2 implements Runnable
{
    private byte[] lock1;
    private byte[] lock2;
    Processer2(byte[] lock1,byte[] lock2){
        this.lock1=lock1;
        this.lock2=lock2;
    }

    public void run(){
        synchronized(lock2){
            System.out.println(Thread.currentThread().getName()+" get lock2,and is waiting for lock1.");
            
            try{
                Thread.sleep(5000);
            }catch(InterruptedException e){
                    e.printStackTrace();
            }

            synchronized(lock1){
                System.out.println(Thread.currentThread().getName()+" has get lock1.");
            }
        }
    }
}

 

结果:

技术分享

两个线程都在等对方释放自己需要的对象锁。

java多线程_死锁的例子

标签:out   roi   gbk   tac   aaa   div   int   abs   and   

原文地址:http://www.cnblogs.com/Allen-win/p/7352883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!