在锁对象期间,会产生一个问题就是死锁,双方都在等在对方释放资源
范例:
public class Test { public static void main(String[] args) throws Exception { MyThread mt1 = new MyThread(); MyThread mt2 = new MyThread(); mt1.flag = 1; mt2.flag = 2; Thread t1 = new Thread(mt1); Thread t2 = new Thread(mt2); t1.start(); t2.start(); } } class MyThread implements Runnable { static Object ob1 = new Object();//注意是static static Object ob2 = new Object();//注意是static int flag = 0; public void run() { if (flag == 1) { System.out.println("flag = 1"); synchronized (ob1) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("休眠中断"); } synchronized (ob2) { System.out.println("1"); } } } if (flag == 2) { System.out.println("flag = 2"); synchronized (ob2) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("休眠中断"); } synchronized (ob1) { System.out.println("2"); } } } } }
时间: 2024-11-06 21:29:55