java线程系列---关于线程同步与互斥问题

例如:子线程运行10次,然后主线程运行100次,按照这样循环50次,如何设计

public class ThreadCommunication {

public static void main(String[] args) {


final Output output = new Output();

//子线程
new Thread(
new Runnable(){
public void run(){
for(int i=1;i<=50;i++){
output.sub(i);
}
}
}).start();
//主线程
for(int i=1;i<=50;i++){
output.main(i);
}
}

}
class Output{
private boolean flag = true;//线程状态
public synchronized void sub(int i){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("子线程第"+i+"次中的"+j);
}
flag = false;
this.notify();//唤醒线程
}

public synchronized void main(int i){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("主线程第"+i+"次中的"+j);
}
flag = true;
this.notify();
}

posted on 2012-04-06 22:35  java课程设计  阅读(174)  评论(0编辑  收藏  举报

导航