線程的死鎖例子

死鎖算法

    不一樣的線程分別佔用對方須要的同步資源不放棄,都在等待對方放棄本身須要的同步資源,就造成了線程的死鎖。app

    出現死鎖後,不會出現異常,不會出現提示,只是全部的線程都處於阻塞狀態,沒法繼續ide

解決方法線程

    專業的算法、原則code

    儘可能減小同步資源的定義資源

    儘可能避免嵌套同步同步

死鎖的例子io

第一個線程鎖住s1等待s2class

第二個線程鎖住s2等待s1方法

package org.zhanghl;
/*
* 演示線程的死鎖問題
* 1.
* */
public class DeadLock {
    public static void main(String[] args) {

        StringBuffer s1=new StringBuffer();
        StringBuffer s2=new StringBuffer();

        new Thread(){
            @Override
            public void run() {
                synchronized (s1){
                    s1.append("a");
                    s2.append("1");

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (s2){
                        s1.append("b");
                        s2.append("2");
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }

            }
        }.start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2){
                    s1.append("c");
                    s2.append("3");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s1){
                        s1.append("d");
                        s2.append("4");
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}
相關文章
相關標籤/搜索