简单事例:妈妈在做饭,突然没盐了,让儿子去买盐

线程1:妈妈

线程2:儿子

妈妈在做饭,突然没盐了,妈妈线程通知儿子买盐,启动儿子线程,儿子买完盐回来,妈妈线程继续运行做饭

package demo5;

妈妈类继承Thread类 实现多线程
public class Mom extends Thread {


public void run(){

try {
System.out.println("妈妈买菜没盐了,让儿子买盐");
Son s=new Son();
s.start();//启动儿子线程
s.join();//调用join方法 儿子线程运行完之后,再执行下面语句
System.out.println("妈妈继续做饭");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


//儿子类

package demo5;


public class Son extends Thread {


public void  run(){
try {
System.out.println("儿子去买盐");
Thread.sleep(2000);//儿子线程睡2s
System.out.println("盐买好了");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}


package demo5;

//测试类
public class Test {


public static void main(String[] args) {

Mom t1=new Mom();
Son t2=new Son();
t1.start();

}
}

多线程并行转为串行线程运行

多线程并行转为串行线程运行

相关文章:

  • 2022-12-23
  • 2021-05-20
  • 2022-02-12
  • 2022-02-07
  • 2022-12-23
  • 2021-10-09
  • 2021-12-08
  • 2021-05-30
猜你喜欢
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-09-16
  • 2021-09-29
相关资源
相似解决方案