package com.swift; public class DeadLock implements Runnable { private boolean flag; DeadLock(boolean flag) { this.flag = flag; } public void run() { while (true) { if (flag) { synchronized ("suo1") { System.out.println(Thread.currentThread().getName()+"if....locka"); synchronized ("suo2") { System.out.println(Thread.currentThread().getName()+"if.....lockb"); } } } else { synchronized ("suo2") { System.out.println(Thread.currentThread().getName()+"else.....lockb"); synchronized ("suo1") { System.out.println(Thread.currentThread().getName()+"else....locka"); } } } } } public static void main(String[] args) { /* * 写一个死锁 */ //只有互相都等待对方放弃资源才会产生死锁 new Thread(new DeadLock(true),"线程1").start(); new Thread(new DeadLock(false),"线程2").start(); } }
同步代码块的锁也可以用对象,如LockA.locka
locka对象为静态 公共