- package cn.itcast.gz;
- /**
- * 一道线程的面试题
- * 子线程循环10次,接着主线程循环100次,接着有回到子线程循环10次,
- * 接着再回到主线程循环100次,如此执行50次
- *
- */
- public class Interview {
- public static void main(String[] args) {
- ThreadTest test = new ThreadTest();
- Thread t1 = new Thread(test);
- Thread t2 = new Thread(test);
- t1.start();
- t2.start();
- }
- }
- class ThreadTest implements Runnable
- {
- private boolean flag = false;
- private int j = 0;
- public synchronized void son()
- {
- int time = 1;
- if(flag)
- try{this.wait();}catch(Exception e){e.printStackTrace();};
- for(int i = 0;i<10;i++)
- {
- System.out.println("sunThread..."+time++);
- }
- flag = true;
- this.notifyAll();
- }
- public synchronized void father()
- {
- int time = 1;
- if(!flag)
- try{this.wait();}catch(Exception e){e.printStackTrace();}
- for(int i = 0;i<100;i++)
- {
- System.out.println("mainThread..."+time++);
- }
- flag = false;
- this.notifyAll();
- }
- @Override
- public void run() {
- for(int i = 0;i<50;i++)
- {
- if(j==0)
- {
- son();
- }else
- {
- father();
- }
- j=(j+1)%2;
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/301220138328.html
来源: http://www.codesnippet.cn/detail/301220138328.html