[Java] java 线程的结合 →→→→→进入此内容的聊天室

来自 , 2020-09-27, 写在 Java, 查看 117 次.
URL http://www.code666.cn/view/48ab2f9b
  1. /**
  2.  * 线程的结合。
  3.  * 当一个线程需要等待另一个线程结束时,叫做线程的结合。
  4.  */
  5. public class JoinThread {
  6.         /**     自定义线程类 */
  7.         static class ThreadA extends Thread{
  8.                 //线程的ID
  9.                 private int ID = 0;
  10.                 //线程运行时循环的次数
  11.                 private int whileTimes = 0;
  12.                 public ThreadA(int id, int times){
  13.                         this.ID = id;
  14.                         this.whileTimes = times;
  15.                 }
  16.                 public void run(){
  17.                         System.out.println("ThreadA" + this.ID + " begin!");
  18.                         int i=0;
  19.                         try {
  20.                                 //连续循环whileTimes次
  21.                                 while (i < this.whileTimes){
  22.                                         System.out.println("ThreadA-" + this.ID + ": " + i++);
  23.                                         //sleep方法将当前线程休眠。
  24.                                         Thread.sleep(200);
  25.                                 }
  26.                         } catch (InterruptedException e) {
  27.                         }
  28.  
  29.                         System.out.println("ThreadA" + this.ID + " end!");
  30.                 }
  31.         }
  32.         public static void main(String[] args) {
  33.                 //新建4个线程对象
  34.                 Thread thread1 = new ThreadA(1, 3);
  35.                 Thread thread2 = new ThreadA(2, 2);
  36.                 Thread thread3 = new ThreadA(3, 2);
  37.                 Thread thread4 = new ThreadA(4, 4);
  38.                 //启动所有线程
  39.                 System.out.println("Main method begin. To start 4 threads!");
  40.                 thread1.start();
  41.                 thread2.start();
  42.                 thread3.start();
  43.                 thread4.start();
  44.                 //等待所有线程运行结束
  45.                 try {
  46.                         thread1.join();
  47.                         thread2.join();
  48.                         thread3.join();
  49.                         thread4.join();
  50.                 } catch (InterruptedException e) {
  51.                         e.printStackTrace();
  52.                 }
  53.                 //此时所有线程都运行结束
  54.                 System.out.println("Main method end! All 4 threads are ended");
  55.         }
  56. }
  57.  

回复 "java 线程的结合"

这儿你可以回复上面这条便签

captcha