マルチスレッド同期(ループ50ベースの深さ版)
7745 ワード
要求:サブスレッドループ10回後メインスレッドループ100回後サブスレッドループ10回.....このように50回往復する
サブスレッドの実行は10回ごとに中断されず、メインスレッドの実行は100回ごとに中断されないので、この2つの操作に同期を加えることができます.
サブスレッドの実行は10回ごとに中断されず、メインスレッドの実行は100回ごとに中断されないので、この2つの操作に同期を加えることができます.
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 }