zoukankan      html  css  js  c++  java
  • 线程中join的用法

     join是Thread类的方法

    /**
    * Waits for this thread to die.
    *
    * @exception InterruptedException if any thread has interrupted
    * the current thread. The <i>interrupted status</i> of the
    * current thread is cleared when this exception is thrown.
    */

    从注解上看  是等待线程死去,即锁住当前线程知道线程死去

    join方法 让线程顺序执行,他内部也是锁的实现机制
     所以join的作用就相当于阻塞掉除了当前线程以外的所有的线程(包括主线程),等待自己执行结束,
     并且遵守先来后到的排队原则,先join的先执行,后join后执行,
     必须注意的是,最后的线程不能使用join,否则线程就全部在等待中,
     所以根据Thread的join()方法的特性,可以实现线程的同步。

    来看一个demo

    public class JoinTest {
    //测试 join()方法是不是线程安全的
    public static void main(String[] args) throws InterruptedException {
    System.out.println("主方法运行:"+Thread.currentThread().getName());
    startFirstThread();
    startSecondThread();
    System.out.println("主方法运行结束"+Thread.currentThread().getName());

    }
    private static void startFirstThread(){
    Thread thread1 = new Thread(){
    @Override
    public void run() {
    for (int i = 0; i < 5; i++){
    System.out.println("线程方法0:"+Thread.currentThread().getName()+ "运行次数"+ i);
    }
    }
    };
    thread1.start();
    try {
    thread1.join();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    private static void startSecondThread(){
    Thread thread2 = new Thread(){
    @Override
    public void run() {
    for (int i = 0; i < 5; i++){
    System.out.println("线程方法1:"+Thread.currentThread().getName()+ "运行次数"+i);
    }
    }
    };
    thread2.start();
    try {
    thread2.join();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    运行结果如下:

    主方法运行:main
    线程方法0:Thread-0运行次数0
    线程方法0:Thread-0运行次数1
    线程方法0:Thread-0运行次数2
    线程方法0:Thread-0运行次数3
    线程方法0:Thread-0运行次数4
    线程方法1:Thread-1运行次数0
    线程方法1:Thread-1运行次数1
    线程方法1:Thread-1运行次数2
    线程方法1:Thread-1运行次数3
    线程方法1:Thread-1运行次数4
    主方法运行结束main

    注释掉   thread1.join(); 和 thread2.join();

    运行结果如下

    主方法运行:main
    主方法运行结束main
    线程方法0:Thread-0运行次数0
    线程方法0:Thread-0运行次数1
    线程方法0:Thread-0运行次数2
    线程方法0:Thread-0运行次数3
    线程方法1:Thread-1运行次数0
    线程方法0:Thread-0运行次数4
    线程方法1:Thread-1运行次数1
    线程方法1:Thread-1运行次数2
    线程方法1:Thread-1运行次数3
    线程方法1:Thread-1运行次数4

    注释掉   thread2.join()  

    运行结果如下

    主方法运行:main
    线程方法0:Thread-0运行次数0
    线程方法0:Thread-0运行次数1
    线程方法0:Thread-0运行次数2
    线程方法0:Thread-0运行次数3
    线程方法0:Thread-0运行次数4
    主方法运行结束main
    线程方法1:Thread-1运行次数0
    线程方法1:Thread-1运行次数1
    线程方法1:Thread-1运行次数2
    线程方法1:Thread-1运行次数3
    线程方法1:Thread-1运行次数4

    可以看到不就join方法  线程执行的顺序是随机的

    加上join方法  main线程在最后执行。

    如果不足,欢迎留言。一起讨论

  • 相关阅读:
    【WP开发】记录屏幕操作
    【.NET深呼吸】清理对象引用,有一个问题容易被忽略
    【WP开发】JSON数据的读与写
    【WP8.1开发】RenderTargetBitmap类的特殊用途
    【WP 8.1开发】How to 图像处理
    【WP8.1开发】用手机来控制电脑的多媒体播放
    【WP 8.1开发】如何动态生成Gif动画
    【WP8.1开发】基于应用的联系人存储
    使用awk处理文本
    PHP数组和字符串的处理函数汇总
  • 原文地址:https://www.cnblogs.com/zjf6666/p/9373355.html
Copyright © 2011-2022 走看看