同步
public class SynchronizeThread extends Thread { private int number; private Object obj; public SynchronizeThread(int number, Object obj) { this.number = number; this.obj = obj; } @Override public void run() { super.run(); synchronized (obj) { for (int i = 0; i < 100; i++) { System.out.println(number + "-" + i); } } } public static void main(String args[]) { Object obj = new Object(); for (int i = 0; i < 3; i++) { new SynchronizeThread(i, obj).start(); } } }死锁
public class DeathThread extends Thread { private int number; private Object objA; private Object objB; public DeathThread(int number, Object objA, Object objB) { this.number = number; this.objA = objA; this.objB = objB; } @Override public void run() { super.run(); synchronized (objA) { System.out.println(number + "--A"); try { sleep(1000); synchronized (objB) { System.out.println(number + "--B"); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String args[]) { Object objA = new Object(); Object objB = new Object(); // 死锁 // new DeathThread(0, objA, objB).start(); // new DeathThread(1, objB, objA).start(); // 不会死锁 new DeathThread(0, objA, objB).start(); new DeathThread(1, objA, objB).start(); } }