面试题
面试题:子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序
- public class ThreadTest {
- public static void main(String[] args){
- new ThreadTest().init();
- }
- public void init(){
- final Business business=new Business();
- new Thread(
- new Runnable() {
- public void run() {
- for(int i=0;i<50;i++){
- business.subThread(i);
- }
- }
- }
- ).start();
- for(int i=0;i<50;i++){
- business.mainThread(i);
- }
- }
- }
- class Business{
- boolean flag=true;
- //主线程
- public synchronized void mainThread(int i){
- if(flag){
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- for(int j=0;j<100;j++){
- System.out.println("主线程:"+"i="+i+"j="+j);
- }
- flag=true;
- this.notify();
- }
- //子线程
- public synchronized void subThread(int i){
- if(!flag){
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- for(int j=0;j<10;j++){
- System.out.println("子线程:"+"i="+i+"j="+j);
- }
- flag=false;
- this.notify();
- }
- }