java线程的join
作者:bin * 线程的join
* 「当前线程」中,执行「其他线程」的join方法,「当前线程」会进入阻塞,待「其他线程」执行结束后,才会往下继续执行
*
* 时用场景:
* 例如需要批量拉取不同接口的数据,然后统一返回
public class Part6 {
public static void main(String[] args) throws Exception{
threadJoin();
threadJoinConcurrent();
}
/**
* 线程的join
* 「当前线程」中,执行「其他线程」的join方法,「当前线程」会进入阻塞,待「其他线程」执行结束后,才会往下继续执行
*
* 时用场景:
* 例如需要批量拉取不同接口的数据,然后统一返回
* @throws Exception
*/
private static void threadJoin() throws Exception{
//1、创建2个线程,放到list里面
List<Thread> threads = IntStream.range(1,3).mapToObj(Part6::create).collect(Collectors.toList());
//2、启动这两个线程
threads.forEach(Thread::start);
//3、执行线程的join方法, 可以通过注释下面的join操作,来对比前后输出
for(Thread thread:threads) {
thread.join();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "#" + i);
shortSleep();
}
}
private static Thread create(int seq){
return new Thread(()->{
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "#" + i);
shortSleep();
}
}, String.valueOf(seq));
}
private static void shortSleep(){
try {
//推荐使用封装的TimeUnit方法
TimeUnit.SECONDS.sleep(1);
}catch (Exception e) {
System.out.println("线程被打断sleep,继续执行");
}
}
/**
* 使用join方法去批量并发拉取数据
*/
private static void threadJoinConcurrent() throws Exception{
List<ThreadData> threadDatas = IntStream.range(1,3).mapToObj(Part6::createThreadData).collect(Collectors.toList());
//开始拉取信息
threadDatas.forEach(ThreadData::start);
//进行阻塞等待
for (ThreadData threadData : threadDatas) {
threadData.join();
}
//逐个获取结果
for (ThreadData threadData : threadDatas) {
threadData.getData();
}
}
public static ThreadData createThreadData(Integer i){
return new ThreadData(String.valueOf(i));
}
}
其中ThreadData为
package com.zengbingo.chapter3;
import java.util.concurrent.TimeUnit;
public class ThreadData extends Thread implements queryInterface{
public ThreadData(String d){
data = d ;
}
private String data = "";
@Override
public String getData() {
System.out.println("获取查询结果" + data);
return null;
}
@Override
public void run(){
System.out.println("做查询操作" + data);
try {
TimeUnit.SECONDS.sleep(1);
}catch (Exception e){
}
System.out.println("查询结束" + data);
}
}
queryInterface为:
package com.zengbingo.chapter3;
public interface queryInterface{
String getData();
}