码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-11-08 19:35:51      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   for   div   on   

要求:子线程循环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 }

 

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

标签:style   blog   io   color   ar   sp   for   div   on   

原文地址:http://www.cnblogs.com/Wen-yu-jing/p/4083857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!