java死锁代码示例

/**
* 线程死锁
* @author 签约test
*
*/
public class TestDeadLock {
/**
* I want to say ,in there the lock1 and the lock2 isn’t
* common lock ,But in there we must notice that the String lock1=””
* and String lock2 = “” is a common lock ,because in the Constant pool
* they are a common string ,so we must realize that if the String value
* is same when we don’t use the keywords “new”,they will be a same final
* field.
*/
private static String lock1 = “”;
private static String lock2 = “1”;

private static class Thread1 extends Thread{
    @Override
    public void run() {
        synchronized(lock1){
            System.out.println("OK,the Thread1 have got the lock \"lock1\" " +
                    "and wait for sleep ,in a moment ,get the lock2 and " +
                    "finish all the work!!!");
            try {
                //Onhn, he is sleeping ,Yeah I know
                sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //now ,I need the lock "lock2"
            synchronized(lock2){
                System.out.println("OK , I am the Thread1 and I have got " +
                        "the \"lock2\" and I will finish all at once");
            }
        }
    }

}
private static class Thread2 extends Thread{
    @Override
    public void run() {
        synchronized(lock2){
            System.out.println("OK,I am the Thread 2 and 1 have got the lock \"lock2\"" +
                    "because I would like to make a deadLock ,Maybe you think I am so" +
                    "foolish ,but I want tell I am having a test ,yeah only  A test" +
                    "in the test I have got the lock \"lock2\"and I know that the Thrad1" +
                    "have got the lock \"lock1\" and I will go in a deadLock" +
                    "Yeah interesting!!!" +
                    "OK let's go");

            synchronized(lock1){
                System.out.println("OK , I am the Thread2 and I know that" +
                        "the demo willn't run because I ....yeah I know " +
                        "A deadLock ,interesting!!!");
            }
        }
    }

}

/**
 * OK ,have a try
 * @param args
 */
public static void main(String[] args) {
    Thread1 th1 = new Thread1();
    Thread2 th2 = new Thread2();
    /**
     * Yeah ,I deem that i should write a note to tell you what happened
     * but I think i have give the note the console ,yeah I have give it 
     * to console ,so I think new i needn't write note .enhn, I tell you
     * all of this 
     */
    //now we must start them ,and the JVM will get them run ,I konw
    //I won't interrupt
    th1.start();
    th2.start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值