需求:

  1. 主线程每隔1s,输出hi,一共3次
  2. 当输出到hi 1时,启动一个子线程(要求实现Runnable),每隔1s输出hello,等该线程输出3次hello后,退出
  3. 主线程继续输出hi.直到主线程退出. ```java package test;

public class Main { public static void main(String[] args) throws InterruptedException { T t = new T(); for (int i = 1; i <= 3; i++) { System.out.println(“hi “ + i); if(i == 1) {//说明主线程输出了5次 hi t.start();//启动子线程 输出 hello… t.join();//立即将t子线程,插入到main线程,让t先执行 } Thread.sleep(1000);//输出一次 hi, 让main线程也休眠1s } } }

class T extends Thread{ int count = 0; @Override public void run() { while(true){ System.out.println(“hello “ + (++count)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(count == 3){ break; } } } } ``` image.png