子线程运行执行10次后,主线程再运行5次,这样交替执行三次

黑马的面试宝典里的经典面试题

/**
 * 子线程运行执行10次后,主线程再运行5次。这样交替执行三遍
 */
public class _02_Interview {

    public static void main(String[] args) {

        Business bussiness = new Business();

        //子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    bussiness.subMethod();
                }
            }
        }).start();

        //主线程
        for (int i = 0; i < 3; i++) {
            bussiness.mainMethod();
        }
    }

}

//这个类是执行任务的类
class Business {

    private boolean flag = false;

    //flagtrue,主线程执行
    public synchronized void mainMethod() {
        //是不是子线程在执行?是,继续等子线程执行完
        while (false == flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //执行主线程任务
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + i);
        }
        //轮到子线程执行了
        flag = false;
        //唤醒子线程。(一共就两个线程,子线程和主线程,所以唤醒的只能是子线程。)
        notify();
    }

    //flagfalse,子线程执行
    public synchronized void subMethod() {
        //是不是主线程在执行?是,继续等主线程执行完
        while (true == flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //执行子线程任务
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + i);
        }
        //轮到主线程执行了
        flag = true;
        //唤醒主线程。(一共就两个线程,子线程和主线程,所以唤醒的只能是主线程。)
        notify();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36819098/article/details/80744744