线程中死锁的demo

/*
虽然同步的出现解决了线程安全问题。
但是也带来了一些弊端:
1,效率会降低。
2,容易引发死锁。

死锁经常出现的状况为:同步嵌套。


*/



class Test implements Runnable { private boolean flag; Test(boolean flag) { this.flag = flag; } public void run() { if(flag) { while(true) { synchronized(MyLock.locka) { System.out.println(Thread.currentThread().getName()+"...if......locka"); synchronized(MyLock.lockb) { System.out.println(Thread.currentThread().getName()+"...if......lockb"); } } } } else { while(true) { synchronized(MyLock.lockb) { System.out.println(Thread.currentThread().getName()+"...else..........lockb"); synchronized(MyLock.locka) { System.out.println(Thread.currentThread().getName()+"...else..........locka"); } } } } } } class MyLock { public static Object locka = new Object(); public static Object lockb = new Object(); } class DeadLockTest { public static void main(String[] args) { Test t1 = new Test(true); Test t2 = new Test(false); Thread th1 = new Thread(t1,"Сǿ"); Thread th2 = new Thread(t2,"κӆ"); th1.start(); th2.start(); } }

  

原文地址:https://www.cnblogs.com/liushisaonian/p/8595264.html