1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class LearnSuspend1 { public static Object iceCream = null;
public static void main(String[] args) throws Exception { LearnSuspend1 sup = new LearnSuspend1(); sup.suspendResumeTest(); }
public void suspendResumeTest() throws Exception { Thread consumerThread = new Thread(() -> { if (iceCream == null) { System.out.println("没有冰激凌, 小朋友不开心, 等待..."); Thread.currentThread().suspend(); }
System.out.println("小朋友买到冰激凌, 开心回家"); }); consumerThread.start(); Thread.sleep(3000L); iceCream = new Object(); consumerThread.resume(); System.out.println("通知小朋友"); }
public void test2_SyncDeadLock() throws Exception { Thread consumerThread = new Thread(() -> { if (iceCream == null) { System.out.println("没有冰激凌, 小朋友不开心, 等待..."); synchronized (this.iceCream) { Thread.currentThread().suspend(); } } System.out.println("小朋友买到冰激凌, 开心回家"); }); consumerThread.start(); Thread.sleep(3000L); iceCream = new Object(); synchronized (this) { consumerThread.resume(); } System.out.println("通知小朋友"); }
public void test3_OrderDeadLock() throws Exception { Thread consumerThread = new Thread(() -> { if (iceCream == null) { try { Thread.sleep(5000L); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println("没有冰激凌, 小朋友不开心, 等待..."); Thread.currentThread().suspend(); } System.out.println("小朋友买到冰激凌, 开心回家"); }); consumerThread.start(); Thread.sleep(3000L); iceCream = new Object(); consumerThread.resume(); System.out.println("通知小朋友"); } }
|