java多线程中子线程与主线程进行轮换

来源:互联网 发布:23周胎儿四维数据 编辑:程序博客网 时间:2024/06/06 03:45

①子线程执行十次 ② 然后主线程执行五十次  ③ 一二两过程循环20次

package com.tb.Test;public class TraditionalThreadCommunication {public static void main(String[] args) {TraditionalThreadCommunication.init();}private static void init() {Business business = new Business();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor(int i=1;i<=20;i++){business.sub(i);}}}).start();for(int i=1;i<=20;i++){business.main(i);}}static class Business{private boolean flag= true;private  synchronized void sub(int i){while(!flag){//防止伪唤醒try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for(int j=1;j<=10;j++){System.out.println("sub thread sequece of "+j+" loop of"+i);}flag= false;this.notify();}private synchronized void main(int i){while(flag){//防止伪唤醒try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for(int j=1;j<=50;j++){System.out.println("main thread sequece of "+j+" loop of"+i);}flag= true;this.notify();}}}


0 0