能解决下面的问题,基本上就能理解线程互斥与同步了。
子线程循环10次,主线程循环100次,接着子线程循环10,主线程循环100次。如此往复循环50次。
1 package cn.lah.thread; 2 3 public class TraditionalThreadCommunication { 4 5 public static void main(String[] args) { 6 7 final Business business = new Business(); 8 new Thread(new Runnable() { 9 public void run() { 10 for (int i = 1; i <= 50; i++) { 11 business.sub(i); 12 } 13 } 14 }).start(); 15 16 for (int i = 1; i <= 50; i++) { 17 business.main(i); 18 } 19 20 } 21 22 } 23 24 //定义一个业务逻辑类,将线程同步相关的方法归于本类,这种设计可以实现高内聚,并能增强代码的健壮性 25 class Business { 26 27 private boolean beShouldSub = true; 28 29 public synchronized void sub(int i) { 30 while (!beShouldSub) { 31 try { 32 this.wait(); 33 } catch (InterruptedException e) { 34 e.printStackTrace(); 35 } 36 } 37 for (int j = 1; j <= 10; j++) { 38 System.out.println("sub Thread" + j + " loop" + i); 39 } 40 beShouldSub = false; 41 this.notify(); 42 } 43 44 public synchronized void main(int i) { 45 while (beShouldSub) { 46 try { 47 this.wait(); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 } 52 for (int j = 1; j <= 100; j++) { 53 System.out.println("main Thread" + j + " loop" + i); 54 } 55 beShouldSub = true; 56 this.notify(); 57 } 58 }
时间: 2024-10-03 02:36:57