欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

线程交互执行(一道面试题),线程执行面试题,package cn.i

来源: javaer 分享于  点击 26541 次 点评:38

线程交互执行(一道面试题),线程执行面试题,package cn.i


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://byrx.net
相关栏目:

用户点评