线程 join

x33g5p2x  于2022-02-24 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(206)

一 点睛

Thread 的 join 方法是一个可中断方法,也就是说有其它线程执行了当前线程的 interrupt 操作,它会捕获到中断信号,并且擦除中断标识,Thread 的 API 为我们提供了三个不同的 join 方法,具体如下。
public final void join() throws InterruptedException

public final synchronized void join(long millis) throws InterruptedException

public final synchronized void join(long millis, int nanos) throws InterruptedException

二 实战

1 代码

package concurrent;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ThreadJoin {
    public static void main(String[] args) {
        // 定义两个线程,并保存到 threads 中
        List<Thread> threads = IntStream.range(1, 3).mapToObj(ThreadJoin::create).collect(Collectors.toList());
        // a 启动这两个线程
        threads.forEach(Thread::start);
        // b 执行这两个线程的 join 方法
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // c main 线程循环输出
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "#" + i);
            shortSleep();
        }
    }

    private static void shortSleep() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static Thread create(int seq) {
        return new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "#" + i);
            }
        }, String.valueOf(seq));
    }
}

2 运行结果

2#0

2#1

1#0

2#2

2#3

2#4

2#5

2#6

2#7

2#8

1#1

2#9

1#2

1#3

1#4

1#5

1#6

1#7

1#8

1#9

main#0

main#1

main#2

main#3

main#4

main#5

main#6

main#7

main#8

main#9

main 线程最后才输出

3 将 b 处 和 c 处之间的代码都注释掉。

main#0

2#0

2#1

2#2

2#3

1#0

2#4

1#1

2#5

1#2

2#6

1#3

2#7

1#4

1#5

1#6

1#7

1#8

2#8

1#9

2#9

main#1

main#2

main#3

main#4

main#5

main#6

main#7

main#8

main#9

自定义的两个线程和main 线程交替输出。

相关文章