题目:子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程100次,如此循环50次,请写出程序。
- 1 public class TraditionalThreadSynchronized2 {
- 2 public static void main(String[] args) throws Exception {
- 3 Demo1 d1 = new Demo1();
- 4 // 子线程
- 5 new Thread(new Runnable() {
- 6
- 7 @Override
- 8 public void run() {
- 9 for (int i = 1; i <= 50; i++) {
- 10 try {
- 11 d1.sub(i);
- 12 } catch (InterruptedException e) {
- 13 // TODO Auto-generated catch block
- 14 e.printStackTrace();
- 15 }
- 16 }
- 17 }
- 18 }).start();
- 19
- 20 // 主线程
- 21 for (int i = 1; i <= 50; i++) {
- 22 d1.main(i);
- 23 }
- 24
- 25 }
- 26 }
- 27
- 28 class Demo1 {
- 29 public Boolean mainDoIt = false;标志主线程方法是否被调用
- 30 // 子线程循环10次
- 31 public synchronized void sub(int i) throws InterruptedException {
- 32 while(mainDoIt) {
- 33 this.wait();
- 34 }
- 35 for (int j = 1; j <= 10; j++) {
- 36 System.out.println("sub" + j + "---SUB" + i);
- 37 }
- 38 mainDoIt=true; //子线程调用完毕
- 39 this.notify();// 唤醒主线程
- 40 }
- 41
- 42 // 主线程循环100次
- 43 public synchronized void main(int i) throws InterruptedException {
- 44 while(!mainDoIt) {
- 45 this.wait();
- 46 }
- 47 for (int j = 1; j <= 100; j++) {
- 48 System.out.println("main" + j + "---MAIN" + i);
- 49 }
- 50 mainDoIt = false;//主线程调用完毕
- 51 this.notify();// 唤醒子线程
- 52
- 53 }
- 54 }
解题思路:子线程语主线程为互斥,可用SYNCHRONIZED。为了体现Java 的高类聚性,最好能将共同数据或共同方法归为同一类,即编写一个类来存放两个同步方法。要让他们交替进行,可用信号量控制,并用wait ,notify 进行线程间通信。