死锁其实开发中并不常用,大部分仅仅是为了应付面试!所以,- public class DeadLock implements Runnable{
- private boolean f ;
- public DeadLock(boolean f){this.f = f;}
- public void run() {
- while(true){
- //死循环,演示2个线程,一个线程中,的f是true 另一个线程的f是false
-
- if(f==true){
- //第一个线程,判断f为true,使用LockA锁
- synchronized(LockA.locka){
- System.out.println("if...locka");//持有LockA锁
- synchronized(LockB.lockb){
- System.out.println("if...lockb");
- }
- }
- }else{
- //第二个线程,判断f为false
- synchronized(LockB.lockb){
- System.out.println("else..lockb");//持有LockB锁
- synchronized(LockA.locka){
- System.out.println("else..locka");
- }
- }
- }
- }
- }
-
- }
- /*
- * 造2个锁
- */
- class LockA{
- public static LockA locka = new LockA();
- }
- class LockB{
- public static LockB lockb = new LockB();
- }
- public class DeadTest {
- /*
- * 测试死锁程序
- */
- public static void main(String[] args) {
- DeadLock d1 = new DeadLock(true);
- DeadLock d2 = new DeadLock(false);
-
- Thread t1 = new Thread(d1);
- Thread t2 = new Thread(d2);
-
- t1.start();
- t2.start();
- }
- }
复制代码 差不多的理解,然后把代码记熟悉了就好!
|
|