多线程同步(循环50 基础加深版)

要求:子线程循环10次后主线程循环100次之后子线程循环10次.....如此往复50次

  子线程的每次执行10次不许被打断以及主线程的每次100次不许被打断 所以这两个操作可以加上同步所

  

 1 package com.thread;
 2 
 3 public class ThreadTest2 {
 4     public static void main(String[] args) {
 5         final Output output = new Output();
 6         new Thread(new Runnable() {
 7             
 8             @Override
 9             public void run() {
10                 for(int i=1;i<=50;i++){
11                     output.printSub(i);
12                 }
13             }
14         }).start();
15         new Thread(new Runnable() {
16             @Override
17             public void run() {
18                 for(int i=1;i<=50;i++){
19                     output.printMain(i);
20                 }
21             }
22         }).start();
23     }
24 }
25 class Output{
26     private boolean isSub = true;
27     public synchronized void printSub(int j){
28         while(!isSub){
29             try {
30                 this.wait();
31             } catch (InterruptedException e) {
32                 // TODO Auto-generated catch block
33                 e.printStackTrace();
34             }
35         }
36         for(int i=1;i<=10;i++){
37             System.out.println("子线程打印:"+i+"-----"+j);
38         }
39         isSub = false;
40         this.notifyAll();
41     }
42     public synchronized void printMain(int j){
43         while(isSub){
44             try {
45                 this.wait();
46             } catch (InterruptedException e) {
47                 e.printStackTrace();
48             }
49         }
50         for(int i=1;i<=100;i++){
51             System.out.println("主线程打印:"+i+"*********"+j);
52         }
53         isSub = true;
54         this.notifyAll();
55     }
56 }
原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4083857.html