zoukankan      html  css  js  c++  java
  • 主子线程

    本文介绍两种主线程等待子线程的实现方式,以5个子线程来说明:

    1、使用Thread的join()方法,join()方法会阻塞主线程继续向下执行。

    2、使用Java.util.concurrent中的CountDownLatch,是一个倒数计数器。初始化时先设置一个倒数计数初始值,每调用一次countDown()方法,倒数值减一,他的await()方法会阻塞当前进程,直到倒数至0。

    本例中 主线程不光能和子线程 协同步调 也可以添加static变量 进行通讯

    join方式代码如下:

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. package com.test.thread;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.List;  
    5.   
    6. public class MyThread extends Thread  
    7. {  
    8.   
    9.     public MyThread(String name)  
    10.     {  
    11.         this.setName(name);  
    12.     }  
    13.   
    14.     @Override  
    15.     public void run()  
    16.     {  
    17.         System.out.println(this.getName() + " staring...");  
    18.   
    19.         System.out.println(this.getName() + " end...");  
    20.     }  
    21.   
    22.     /** 
    23.      * @param args 
    24.      */  
    25.     public static void main(String[] args)  
    26.     {  
    27.         System.out.println("main thread starting...");  
    28.   
    29.         List<MyThread> list = new ArrayList<MyThread>();  
    30.   
    31.         for (int i = 1; i <= 5; i++)  
    32.         {  
    33.             MyThread my = new MyThread("Thrad " + i);  
    34.             my.start();  
    35.             list.add(my);  
    36.         }  
    37.   
    38.         try  
    39.         {  
    40.             for (MyThread my : list)  
    41.             {  
    42.                 my.join();  
    43.             }  
    44.         }  
    45.         catch (InterruptedException e)  
    46.         {  
    47.             e.printStackTrace();  
    48.         }  
    49.   
    50.         System.out.println("main thread end...");  
    51.   
    52.     }  
    53.   
    54. }  

    运行结果如下:

    main thread starting...
    Thrad 2 staring...
    Thrad 2 end...
    Thrad 4 staring...
    Thrad 4 end...
    Thrad 1 staring...
    Thrad 1 end...
    Thrad 3 staring...
    Thrad 3 end...
    Thrad 5 staring...
    Thrad 5 end...
    main thread end...

  • 相关阅读:
    Openstack Paste.ini 文件详解
    Keystone controller.py & routers.py代码解析
    YARN源码分析(三)-----ResourceManager HA之应用状态存储与恢复
    YARN源码分析(四)-----Journalnode
    YARN源码分析(四)-----Journalnode
    YARN源码分析(四)-----Journalnode
    YARN源码学习(五)-----NN,DN,RM在Ganglia上的监控实现机理
    Confluence 6 配置一个 Confluence 环境
    Confluence 6 审查日志的对象
    Confluence 6 审查日志
  • 原文地址:https://www.cnblogs.com/lnas01/p/5948336.html
Copyright © 2011-2022 走看看