一、main函數
package com.sdmjhca.springBootDemo.deadlock; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author JHMI on 2017/8/20 0020. * 此種生成死鎖的方式注意下列問題: * 1、測試類內部定義的對象不能是靜態的 * 2、synchronized必須是嵌套鎖 */ public class DeadLockMain { public static void main(String args[]) throws InterruptedException { /*DeadLoakTest t1 = new DeadLoakTest(true); DeadLoakTest t2 = new DeadLoakTest(false); t1.start(); t2.start();*/ /*ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(t1); executor.execute(t2);*/ Object o1 = new String("11111111111111111"); Object o2 = new String("22222222222222"); DeadLoakTest2 test2 = new DeadLoakTest2(o1,o2); //Thread.sleep(1000); DeadLoakTest2 test21 = new DeadLoakTest2(o2,o1); test2.start(); test21.start(); } }二、兩種測試類寫法
package com.sdmjhca.springBootDemo.deadlock; /** * @author JHMI on 2017/8/20 0020. */ public class DeadLoakTest extends Thread { boolean flag; public DeadLoakTest(boolean temp){ flag = temp; } public void run(){ if(flag){ lock(Resource.o1,Resource.o2); }else{ lock(Resource.o2,Resource.o1); } } public void lock(Object o1,Object o2){ synchronized (o1){ System.out.println("已經獲得對象1的鎖,"+o1); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2){ System.out.println("已經獲得對象2的鎖,"+o2); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
package com.sdmjhca.springBootDemo.deadlock; /** * @author JHMI on 2017/8/20 0020. * 此種生成死鎖的方式注意下列問題: * 1、測試類內部定義的對象不能是靜態的 * 2、synchronized必須是嵌套鎖 */ public class DeadLoakTest2 extends Thread { boolean flag; //局部變量是線程私有的 Object o1; Object o2; /** * 此處注意不能使用static修飾符, */ //static靜態變量和常量是線程公有的 static Object o3; static Object o4; public DeadLoakTest2(boolean temp){ flag = temp; } public DeadLoakTest2(Object o1,Object o2){ this.o1 = o1; this.o2 = o2; } public void run(){ lock(o1,o2); } public void lock(Object o1,Object o2){ synchronized (o1){ System.out.println("已經獲得對象1的鎖,"+o1); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2){ System.out.println("已經獲得對象2的鎖,"+o2); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
package com.sdmjhca.springBootDemo.deadlock; /** * @author JHMI on 2017/8/20 0020. */ public class Resource { static final Object o1 = new String("1111"); static final Object o2 = new String("2222"); }