//线程编程:子线程先运行 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