主线程等待子线程结束

主线程怎样等待所有子线程执行完?主线程怎样获得子线程的运行结果?

直接贴代码了:

package com.ly.demo.thread;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;


/**
 * 线程类
 * 可以实现Runnable接口也可以继承Thread类
 * 推荐实现Runnable接口,这样的话MyThread类还可以去继承其他的类
 * @author liuyang
 *
 */
public class MyThread implements Runnable
{
private CountDownLatch latch;
private List<String> returnList = new ArrayList<String>();

/**
* 无参构造器
*/
public MyThread() {}

public MyThread(CountDownLatch latch) 
{
this.latch = latch;
}

/**
* 线程执行的方法
*/
@Override
public void run() 
{
this.returnList = getResult();
//线程执行完将正在运行的线程数量减去1
this.latch.countDown();
}

private List<String> getResult() 
{
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
return list;
}


public List<String> getReturnList() 
{
return returnList;
}


public void setReturnList(List<String> returnList) 
{
this.returnList = returnList;
}
}


package com.ly.demo.thread;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;


/**
 * 实例化多线程,并启动
 * @author liuyang
 *
 */
public class MainTest 
{
//定义启动的线程个数
private static final int THREAD_NUM = 3;
private static List<MyThread> myThreadList = new ArrayList<MyThread>();
private static List<String> resultList = new ArrayList<String>();

public static void main(String[] args) throws Exception 
{
CountDownLatch latch = new CountDownLatch(THREAD_NUM);
//实例化线程,并启动
for(int i=0;i<THREAD_NUM;i++) 
{
MyThread myThread = new MyThread(latch);
Thread thread = new Thread(myThread);
myThreadList.add(myThread);
thread.start();
}
//等到所有子线程执行完
latch.await();
//所有子线程执行完了对结果汇总
for(MyThread myThread:myThreadList) 
{
resultList.addAll(myThread.getReturnList());
}
System.out.println(resultList.size());//9
System.out.println(resultList);//[111, 222, 333, 111, 222, 333, 111, 222, 333]
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值