死锁,同步 TestSync.java package Thread; public class TestSync implements Runnable{ Timer timer = new Timer(); public static void main(String[] args) { TestSync test = new TestSync(); Thread t1 = new Thread(test); Thread t2 = new Thread(test); t1.setName("t1"); t2.setName("t2"); t1.start(); t2.start(); } public void run() { timer.add(Thread.currentThread().getName()); } } class Timer{ private static int num = 0; public void add(String name){ synchronized(this){ //此处使用同步 互斥锁,否则调用t2相同 num++; try { Thread.sleep(1); } catch (Exception e) {} System.out.println(name+ "这是第"+num+"个Timer的add方法"); } } } 理解死锁 TestDeadLock.java package Thread; //模拟死锁,1个线程类模拟2个线程 public class TestDeadLock implements Runnable { public int flag = 1; static Object o1 = new Object(), o2 = new Object(); public void run() { System.out.println("flag =" + flag); synchronized (o1) { try { Thread.sleep(500); } catch (Exception e) { } synchronized (o2) { try { Thread.sleep(500); } catch (Exception e) { System.out.println("1"); } } } if (flag == 0) { synchronized (o2) { try { Thread.sleep(500); } catch (Exception e) { } synchronized (o1) { try { Thread.sleep(500); } catch (Exception e) { System.out.println("0"); } } } } } public static void main(String[] args) { TestDeadLock td1 = new TestDeadLock(); TestDeadLock td2 = new TestDeadLock(); td1.flag = 1; td2.flag = 2; Thread t1 = new Thread(td1); Thread t2 = new Thread(td2); t1.start(); t2.start(); } } 一道面试题,理解直行顺序,程序死锁后,仍然可以直行其他方法 package Thread; public class TT implements Runnable { int b = 100 ; public synchronized void m1() throws Exception{ b = 1000; Thread.sleep(5000); System.out.println("b = "+b); } public void m2(){ System.out.println(b); } public void run() { try { m1(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception{ TT tt = new TT(); Thread t = new Thread(tt); t.start(); Thread.sleep(1000); tt.m2(); Thread.sleep(6000); } }