赞
踩
主线程怎样等待所有子线程执行完?主线程怎样获得子线程的运行结果?
直接贴代码了:
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]
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。