java for循环 多线程_Java - 用For循环创建多个线程

本文展示了如何在Java中使用ExecutorService和for循环创建并行线程。通过ExecutorService,可以更有效地管理线程池,提高性能。示例代码创建了一个固定大小的线程池,并使用for循环提交任务。每个任务是实现了Runnable接口的MyRunnable类,它打印出任务ID和当前线程名称。运行示例时,可以看到线程并行执行。
摘要由CSDN通过智能技术生成

示例代码更好的选择:

import java.util.concurrent.*;

public class ExecutorTest{

public static void main(String args[]){

int numberOfTasks = Integer.parseInt(args[0]);

ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

try{

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

executor.execute(new MyRunnable(i));

}

}catch(Exception err){

err.printStackTrace();

}

executor.shutdown(); // once you are done with ExecutorService

}

}

class MyRunnable implements Runnable{

int id;

public MyRunnable(int i){

this.id = i;

}

public void run(){

try{

System.out.println("Runnable started id:"+id);

System.out.println("Run: "+ Thread.currentThread().getName());

System.out.println("Runnable ended id:"+id);

}catch(Exception err){

err.printStackTrace();

}

}

}

用法:

java ExecutorTest 2

Runnable started id:0

Run: pool-1-thread-1

Runnable ended id:0

Runnable started id:1

Run: pool-1-thread-2

Runnable ended id:1

相关文章:(使用ExecutorService的优点作为普通的替代品Thread)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值