当前位置:   article > 正文

主线程等待子线程结束_python 主线程内开子线程,主线程等待子线程结束

python 主线程内开子线程,主线程等待子线程结束

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

直接贴代码了:

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]
}
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/768907
推荐阅读
相关标签
  

闽ICP备14008679号