許久沒來這裏了,今天找了個面試題,隨便搞搞
/** * 子線程循環10次,接着主線程循環100,接着子線程循環10次,接着主線程循環100,如此循環50次 * @author lenovo * */ public class Test2 { public static void main(String[] args) { final MyThread myThread = new MyThread(); new Thread( new Runnable(){ @Override public void run() { for(int i=0;i<50;i++){ System.out.println("sub is "+i +" count"); myThread.sub(); } } }).start(); for (int i = 0; i < 50; i++) { System.out.println("main is "+i +" count"); myThread.main(); } } }
/** * 線程類 * @author lenovo * */ class MyThread{ /** * 標誌子線程調用方法是否被調用 */ private boolean bSubIsRuned = true; /** * 子線程調用方法 */ public synchronized void sub(){ while(!bSubIsRuned){//若是子線程方法沒被調用,即調用了主線程方法 //等待別的線程使用 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for(int i = 0 ;i<10;i++){ System.out.println("sub:" + i); } //子方法被調用完成後 bSubIsRuned = false; //喚醒別的在等待的線程 this.notify(); } /** * 主線程調用方法 */ public synchronized void main(){ while(bSubIsRuned){//若是主方法沒被調用,即子方法被調用 try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i = 0 ;i<100;i++){ System.out.println("main:" + i); } bSubIsRuned = true; this.notify(); } }