Java线程——线程习题(一)子线程执行10次后,主线程再运行5次,这样交替执行三遍

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

代码如下:

package com.itheima.gan;
/**
 *  子线程执行10次后,主线程再运行5次,这样交替执行三遍
 * @author 12428
 *
 */
public class Test {
    public static void main(String[] args) {
        final Bussiness bussiness=new Bussiness();
        //创建一个子线程,run方法里面子线程执行3变
        new Thread(new Runnable() {
            public void run() {
                for(int i=0;i<3;i++) {
                    bussiness.subMethod();
                }
            }
        }).start();
        
        //主线程
        for(int i=0;i<3;i++) {
            bussiness.mainMethod();
        }
    }
    
}

class Bussiness{
    //创建一个私有的标识位
    private boolean subFlag=true;
    
    public synchronized void mainMethod() {
        
        while(subFlag) {
            try {
                //标识为true 就等待,释放所持有的锁,让另一个线程执行,直到被唤醒才继续执行下去
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        //如果当前的标志位不为true
        //就向下执行
        for(int i=0;i<5;i++) {
            System.out.println(Thread.currentThread().getName()+" : main thread running loop count --"+i);
            try {
                //线程休眠1s,再执行
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //执行完上面的循环后再把标志位改为true,防止这个线程两次连续执行
        subFlag=true;
        notify();
    }


    public synchronized void subMethod() {
        //如果标识位为false
        //就执行等待,让另一个线程执行,直到被唤醒
        while(!subFlag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        //如果标识为true
        //向下执行
        for(int i=0;i<10;i++) {
            System.out.println(Thread .currentThread().getName()+" : sub thread runnig loop count -- "+i);
            //每执行一次就休眠1s
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        //执行完一个循环后就将标识为改为false,防止这个线程连续两次执行
        subFlag=false;
        notify();
        
    }
    
}

  运行结果:

     

   

 

  

猜你喜欢

转载自www.cnblogs.com/zhilili/p/11970954.html