首页 > 其他 > 详细

子线程先运行 3 次,然后主线程运行 5 次,如此反复运行 10 次

时间:2014-02-28 15:01:06      阅读:336      评论:0      收藏:0      [点我收藏+]

//线程编程:子线程先运行 3 次,然后主线程运行 5 次,如此反复运行 10 次。

class Business
{ //控制由谁执行
boolean bShouldSub = true;

public synchronized void MainThread(int i){
if(bShouldSub){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
for(int j=0; j<5; j++){
System.out.println(Thread.currentThread().getName()+
"-->i="+i + ",j="+j);
}
bShouldSub = true;
this.notify();
}


public synchronized void SubThread(int i){
if(!bShouldSub){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
for(int j=0; j<3; j++){
System.out.println(Thread.currentThread().getName()+
"->i="+i + ",j="+j);
}
bShouldSub = false;
this.notify();
}
}

public class ThreadProject
{
public static void main(String args[]){

ThreadProject tp = new ThreadProject();
tp.init();
}

public void init(){

final Business business = new Business();
new Thread(
new Runnable(){

public void run(){
for(int i=0; i<10; i++){
//调用子线程中的方法
business.SubThread(i);
}
}
}).start();

for(int i=0; i<10; i++){
business.MainThread(i);
}
}
}

子线程先运行 3 次,然后主线程运行 5 次,如此反复运行 10 次,布布扣,bubuko.com

子线程先运行 3 次,然后主线程运行 5 次,如此反复运行 10 次

原文:http://www.cnblogs.com/zfg-technology/p/3572416.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!