线程面试题

面试题
面试题:子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次,请写出程序
  1.     public class ThreadTest {
  2.     public static void main(String[] args){
  3.         new ThreadTest().init();
  4.     }
  5.     public void init(){
  6.         final Business business=new Business();
  7.         new Thread(
  8.             new Runnable() {
  9.                 public void run() {
  10.                     for(int i=0;i<50;i++){
  11.                         business.subThread(i);
  12.                     }
  13.                 }
  14.             }
  15.         ).start();
  16.         for(int i=0;i<50;i++){
  17.             business.mainThread(i);
  18.         }
  19.     }
  20. }
  21. class Business{
  22.     boolean flag=true;
  23.     //主线程
  24.     public synchronized void mainThread(int i){
  25.         if(flag){
  26.             try {
  27.                 this.wait();
  28.             } catch (InterruptedException e) {
  29.                 // TODO Auto-generated catch block
  30.                 e.printStackTrace();
  31.             }
  32.         }
  33.         for(int j=0;j<100;j++){
  34.             System.out.println("主线程:"+"i="+i+"j="+j);
  35.         }
  36.         flag=true;
  37.         this.notify();
  38.     }
  39.     //子线程
  40.     public synchronized void subThread(int i){
  41.         if(!flag){
  42.             try {
  43.                 this.wait();
  44.             } catch (InterruptedException e) {
  45.                 // TODO Auto-generated catch block
  46.                 e.printStackTrace();
  47.             }
  48.         }
  49.         for(int j=0;j<10;j++){
  50.             System.out.println("子线程:"+"i="+i+"j="+j);
  51.         }
  52.         flag=false;
  53.         this.notify();
  54.     }
  55. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值