java多线程创建runnable_Java线程池和runnables创建runnables

有很多方法可以做你想要的 . 您需要小心,不要最终创建太多线程 .

以下是一个示例,您可以使用ExecutorCompletionService提高效率,也可以使用Runnable .

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class ThreadsMakeThreads {

public static void main(String[] args) {

new ThreadsMakeThreads().start();

}

public void start() {

//Create resources

ExecutorService threadPool = Executors.newCachedThreadPool();

Random random = new Random(System.currentTimeMillis());

int numberOfThreads = 5;

//Prepare threads

ArrayList leaders = new ArrayList();

for(int i=0; i < numberOfThreads; i++) {

leaders.add(new Leader(threadPool, random));

}

//Get the results

try {

List> results = threadPool.invokeAll(leaders);

for(Future result : results) {

System.out.println("Result is " + result.get());

}

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

e.printStackTrace();

}

threadPool.shutdown();

}

class Leader implements Callable {

private ExecutorService threadPool;

private Random random;

public Leader(ExecutorService threadPool, Random random) {

this.threadPool = threadPool;

this.random = random;

}

@Override

public Integer call() throws Exception {

int numberOfWorkers = random.nextInt(10);

ArrayList workers = new ArrayList();

for(int i=0; i < numberOfWorkers; i++) {

workers.add(new Worker(random));

}

List> tasks = threadPool.invokeAll(workers);

int result = 0;

for(Future task : tasks) {

result += task.get();

}

return result;

}

}

class Worker implements Callable {

private Random random;

public Worker(Random random) {

this.random = random;

}

@Override

public Integer call() throws Exception {

return random.nextInt(100);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值