zoukankan      html  css  js  c++  java
  • 多线程中的join()方法

    在java的多线程中有一个join()方法,作用是等待其他的线程结束。一直不明白是怎么回事,今天查了一下资料才了解,简单的说一下吧。

    join()方法是java多线程中的一种协作机制,比如我们现在有一个线程运行着,运行到了某个位置,我们需要另外一个线程返回的人结果,这个时候,我们就需要在当前线程中调用另外一个线程的join()方法,注意是另外一个线程的join()方法,表示当前线程需要等待另外一个线程的完成。等到另外一个线程完成之后,再从join()方法的后面开始执行

    一个简单的demo如下:

    package com.app.basic;
    
    /**
     * Created by Charles on 2016/2/1.
     */
    public class JoinMotion {
    
        public static void main(String[] args) {
    
            final Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 5; i++) {
                        System.out.println("current thread is:"+Thread.currentThread().getName());
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }
                }
            });
    
            final Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                  for(int i =0; i < 7;i++){
                      System.out.println("current thread is:"+Thread.currentThread().getName());
                      try {
                          Thread.sleep(1000);
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
                      if(i == 3){
                          try {
                              t1.join();
                          } catch (InterruptedException e) {
                              e.printStackTrace();
                          }
                      }
                  }
                }
            });
    
            t1.start();
            t2.start();
    
        }
    }
    

    返回的结果如下:

    current thread is:Thread-0
    current thread is:Thread-1
    current thread is:Thread-0
    current thread is:Thread-1
    current thread is:Thread-0
    current thread is:Thread-1
    current thread is:Thread-0
    current thread is:Thread-1
    current thread is:Thread-0
    current thread is:Thread-1
    current thread is:Thread-1
    current thread is:Thread-1
  • 相关阅读:
    ML
    python常用库函数
    ML神器:sklearn的快速使用
    分类算法
    离散型特征编码方式:one-hot与哑变量*
    LR多分类推广
    细品
    特征提取方法: one-hot 和 TF-IDF
    【数据化运营模型】目标客户的预测(响应、分类)模型
    【转】 Python 中,matplotlib绘图无法显示中文的问题
  • 原文地址:https://www.cnblogs.com/summerpxy/p/13648341.html
Copyright © 2011-2022 走看看