关于java线程的经典面试题。主线程子线程交替执行n次

子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次

package com.lyf.practice;

/**
 * Created by fangjiejie on 2017/4/24.
 */
public class ThreadTest2 {
    private class Business{
        boolean flag=true;//作为子线程和主线程谁来执行的标志,true为子线程执行,主线程等待
        public synchronized void SubThread(int i){
            if(!flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int j=0;j<10;j++){
                System.out.println("子线程"+i+"执行"+j);
            }
            this.notifyAll();
            flag=false;
        }
        public synchronized void MainThread(int i){
            if(flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for(int j=0;j<100;j++){
                System.out.println("主线程"+i+"执行"+j);
            }
            this.notifyAll();
            flag=true;
        }
    }
    public void execute(){//主线程子线程轮回执行50次
        final Business business=new Business();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=0;i<50;i++){
                    business.SubThread(i);
                }
            }
        }).start();
        for(int i=0;i<50;i++){//两个循环只能有一个来用线程启动,否则。如果都用new Thread的方式,
            // 一旦一个线程开启,第二个线程必须等待其完成才能开启,发生了死锁现象。
            business.MainThread(i);
        }
    }
    public static void main(String[] args) {
          new ThreadTest2().execute();
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值