编程题目:
2.子线程循环10次,接着主线程循环5次,接着又回到子线程循环10次,接着再回到主线程又循环5次,如此循环50次,请写出程序。
示例代码:
package program.thread.exercise02;
/**
* 2.子线程循环10次,接着主线程循环5次,接着又回到子线程循环10次,接着再回到主线程又循环5次,如此循环50次,请写出程序。
*/
public class ThreadManager {
public static void main(String[] args) {
Business business = new Business();
new Thread(
new Runnable(){
public void run() {
for(int i=0;i<50;i++){
business.subThread(i);
business.mainThread(i);
}
}
}
).start();
}
}
class Business {
boolean should = true;
public synchronized void mainThread(int i){
if(should){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=0;j<5;j++){
System.out.println("主线程:i="+i+",j="+j);
}
should = true;
this.notify();
}
public synchronized void subThread(int i){
if(!should){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j=0;j<10;j++){
System.out.println("子线程:i="+i+",j="+j);
}
should = false;
this.notify();
}
}
结果显示: