java多线程_死锁的例子

/*说明:零长度的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.");
            }
        }
    }
}

结果:

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

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