使用join和CountDownLatch来等待线程结束

1.join方法的实现

join只能在start()之后调用,
调用线程会等待子线程结束后再运行
public class ThreadJoinTest {

    public static void main(String[] args) {
        int count = 100;
        Thread[] threads = new Thread[count];
        IntStream.range(0, count)
                .forEach(i -> {
                    threads[i] = new Thread("thread" + i) {
                        @Override
                        public void run() {
                            ThreadJoinTest.sleep(1);
                            System.out.println(Thread.currentThread().getName() + ":" + i);
                        }
                    };

                    threads[i].start();
                });

        //join只能在start()之后调用
        //调用线程会等待子线程结束后再运行
        Arrays.stream(threads).forEach(ThreadJoinTest::join);
        System.out.println("over");
}
private static void sleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException ex) {

        }
    }

    private static void join(Thread thread) {
        try {
            thread.join();
        } catch (InterruptedException ex) {

        }
    }

测试结果如下

thread2:2
thread10:10
thread6:6
thread14:14
thread18:18
thread34:34
thread22:22
thread26:26
thread30:30
thread38:38
thread42:42
thread46:46
thread50:50
thread54:54
thread62:62
thread66:66
thread58:58
thread70:70
thread74:74
thread78:78
thread82:82
thread86:86
thread90:90
thread94:94
thread98:98
thread5:5
thread1:1
thread9:9
thread13:13
thread17:17
thread21:21
thread25:25
thread29:29
thread33:33
thread37:37
thread41:41
thread45:45
thread49:49
thread61:61
thread57:57
thread53:53
thread77:77
thread73:73
thread69:69
thread65:65
thread93:93
thread89:89
thread85:85
thread81:81
thread97:97
thread0:0
thread12:12
thread4:4
thread8:8
thread16:16
thread20:20
thread24:24
thread28:28
thread32:32
thread36:36
thread40:40
thread44:44
thread60:60
thread56:56
thread52:52
thread48:48
thread76:76
thread72:72
thread68:68
thread64:64
thread92:92
thread88:88
thread84:84
thread80:80
thread96:96
thread3:3
thread7:7
thread11:11
thread99:99
thread95:95
thread91:91
thread87:87
thread83:83
thread79:79
thread75:75
thread67:67
thread63:63
thread71:71
thread59:59
thread51:51
thread55:55
thread23:23
thread27:27
thread31:31
thread35:35
thread39:39
thread43:43
thread47:47
thread15:15
thread19:19
over

2. java.util.concurrent.CountDownLatch

public class ThreadJoinTest {

    public static void main(String[] args) {
        int count = 100;
        Thread[] threads = new Thread[count];

        java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch(count);
        IntStream.range(0, count)
                .forEach(i -> {
                    threads[i] = new Thread("thread" + i) {
                        @Override
                        public void run() {
                            ThreadJoinTest.sleep(1);
                            System.out.println(Thread.currentThread().getName() + ":" + i);                            //只能在run方法的最后一句,或者在 try..finally的 finally里
                            countDownLatch.countDown();
                        }
                    };

                    threads[i].start();
                });
        try {
            countDownLatch.await();
        } catch (InterruptedException ex) {

        }
        System.out.println("over");
    }

原文地址:https://www.cnblogs.com/zhshlimi/p/10929295.html

时间: 2024-08-06 08:20:24

使用join和CountDownLatch来等待线程结束的相关文章

编写多线程代码时,启动线程后等待线程结束方法

在编写多线程代码时,如果主线程结束,那么子线程也会随之结束,如何等待线程结束再往下执行.   等待线程执行完成代码.   线程代码:   package demo; import java.util.concurrent.CountDownLatch; public class NodeSqlThread1 implements Runnable{         private CountDownLatch cdlSync;         public NodeSqlThread1(Coun

等待线程结束

正常环境下等待线程结束 如果需要等待线程结束,就在线程的实例对象上调用join().在管理线程之创建线程最后的例子中,用my_thread.join()代替my_thread.detach()就可以确保在函数终止前.局部变量析构前,线程会终止.在这种情况下,用分开的线程来运行函数就没有什么意义了.因为在等待my_thread终止时,这个线程就不做任何事情了.在实际的工程应用中,要么这个线程做自己的事,要么创建多个线程等待它们结束. join()是简单粗暴的,或者你等待线程终止,或者你不等待.如果

等待线程结束(join)

很多情况下,线程之间的协作和人与人之间的协作非常相似.一种非常常见的合作方式就是分工合作.以我们非常熟悉的软件开发为例,在一个项目进行时,总是应该有几位号称是"需求分析师"的同事,先对系统的需求和功能点进行整理和总结,然后,以书面形式给出一份需求说明或者类似的参考文档,然后,软件设计师,研发工程师才会一拥而上,进行软件开发.如果缺少需求分析师的工作输出,那么软件研发的难度可能会比较大.因此,作为一名软件研发人员,总是喜欢等待需求分析师完成他应该完成的任务后,才愿意投身工作.简单地说,就

python之 启动一个子进程并等待其结束

#_*_coding:utf-8_*_ from multiprocessing import Process import os def aaa(name):     print "此刻运行的函数是由子进程运行,名字(%s), 子进程ID是(%s)" % (name, os.getpid()) if __name__ == "__main__":     print "父进程 (%s) 启动..." % (os.getpid())     p 

C# 多线程join的用法,等待多个子线程结束后再执行主线程

等待多个子线程结束后再执行主线程 class MultiThread{ #region join test public void MultiThreadTest() { Thread[] ths = new Thread[2]; ths[0] = new Thread(Method1); ths[1] = new Thread(Method2); foreach (Thread item in ths) { //首先让所有线程都启动 item.Start(); //试想一下在这里加上item.

Java Thread.join()详解--父线程等待子线程结束后再结束

目录(?)[+] 阅读目录 一.使用方式. 二.为什么要用join()方法 三.join方法的作用 join 四.用实例来理解 打印结果: 打印结果: 五.从源码看join()方法 join是Thread类的一个方法,启动线程后直接调用,例如: ? 1 Thread t = new AThread(); t.start(); t.join(); 回到顶部 在很多情况下,主线程生成并起动了子线程,如果子线程里要进行大量的耗时的运算,主线程往往将于子线程之前结束,但是如果主线程处理完其他的事务后,需

Java 如何实现线程间通信?(notify、join、CountdownLatch、CyclicBarrier、FutureTask、Callable )

转自:https://mp.weixin.qq.com/s?__biz=MzI4Njc5NjM1NQ==&mid=2247486499&idx=1&sn=d3f2d6959df7299bfbe2d663f6c4d353&chksm=ebd6330fdca1ba19316e89bedcaab01be8fdb81ba7ba3a9456c51fa28e80b2b1b33265d513ee&mpshare=1&scene=23&srcid=0113bUJHO

java并发系列(二)-----线程之间的协作(wait、notify、join、CountDownLatch、CyclicBarrier)

在java中,线程之间的切换是由操作系统说了算的,操作系统会给每个线程分配一个时间片,在时间片到期之后,线程让出cpu资源,由其他线程一起抢夺,那么如果开发想自己去在一定程度上(因为没办法100%控制它)让线程之间互相协作.通信,有哪些方式呢? wait.notify.notifyAll 1.void wait( ) 导致当前的线程等待,直到其他线程调用此对象的notify( ) 方法或 notifyAll( ) 方法 2.void wait(long timeout) 导致当前的线程等待,直到

CountDownLatch用法---等待多个线程执行完才执行

CountDownLatch用法---等待多个线程执行完才执行 一.CountDownLatch用法 CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能.比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了. CountDownLatch类只提供了一个构造器: 1 public CountDownLatch(int count) {  };  //参数count为计数值