zoukankan      html  css  js  c++  java
  • 一个关于java线程的面试题

    闲着没事干,在网上看一些面试题,找到一个比较经典的面试题,自己动手写了写。

    题目: 子线程循环10次, 接着主线程循环100次, 接着子线程再循环10次, 接着主线程再循环100次,如此循环50次, 请写出程序 !

    于是我自己研究了一下写了如下代码,也许还不是很完美吧,自我认为已经差不多了。

    代码如下
     1 public class ThreadQuestion {
    2 public static void main(String[] args) {
    3 new ThreadQuestion().init();
    4 }
    5
    6 private void init(){
    7 final Business business=new Business();
    8 new Thread(new Runnable() {
    9 public void run() {
    10 for (int i = 1; i <=50 ; i++) {
    11 business.sub(i);
    12 }
    13 }
    14 }).start();
    15
    16 for (int i = 1; i <=50 ; i++) {
    17 business.main(i);
    18 }
    19 }
    20
    21 class Business{
    22 boolean subDone=true;
    23 public synchronized void sub(int i){
    24 while(!subDone){
    25 try {
    26 this.wait();
    27 } catch (InterruptedException e) {
    28 e.printStackTrace();
    29 }
    30 }
    31 for (int j = 1; j <=10; j++) {
    32 System.out.println("子线程循环第"+j+"次 第"+i+"次循环");
    33 }
    34 subDone=false;
    35 this.notify();
    36 }
    37 public synchronized void main(int i){
    38 while(subDone){
    39 try {
    40 this.wait();
    41 } catch (InterruptedException e) {
    42 e.printStackTrace();
    43 }
    44 }
    45 for (int j = 1; j <=100; j++) {
    46 System.out.println("主线程循环第"+j+"次 第"+i+"次循环");
    47 }
    48
    49 subDone=true;
    50 this.notify();
    51 }
    52 }
    53 }


     

  • 相关阅读:
    下拉框插件开发 (一)
    工厂模式 抽象工厂模式
    闭包 构建函数 简单工厂模式
    js继承
    浅谈js观察者模式
    浅谈js单例模式
    localstorage本地存储
    Vi 配置文件
    Vi Command
    我的Firs博客
  • 原文地址:https://www.cnblogs.com/Laupaul/p/2371883.html
Copyright © 2011-2022 走看看