java死锁代码示例

来源:互联网 发布:android源码查看版本 编辑:程序博客网 时间:2024/05/21 03:26

/**
* 线程死锁
* @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();}

}

1 0