• 多线程中的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
  • 相关阅读:
    archlinux安装nvidia-1050ti闭源驱动教程,亲测
    键盘键码对照
    解决manjaro无法外接显示器
    windows下的上帝模式,很好用,细想,很恐怖啊
    高效率编辑器 Vim——操作篇,非常适合 Vim 新手
    linux rand application
    数组和对象常用API
    JsBridge的异步不执行的处理--promise异步变同步
    js根据数组对象中某个元素合并数组
    js/vue 高德地图绘制驾车路线图
  • 原文地址:https://www.cnblogs.com/summerpxy/p/13648341.html
Copyright © 2020-2023  润新知