java 5 线程池
1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 4 public class ThreadPoolTest 5 { 6 public static void main(String[] args) 7 { 8 ExecutorService threadPool = Executors.newFixedThreadPool(3); 9 10 for(int i = 0; i < 10; i++) 11 { 12 final String taskName = "task " + i; 13 threadPool.execute(new Runnable() 14 { 15 public void run() 16 { 17 System.out.println(Thread.currentThread().getName() + "-" + taskName); 18 } 19 }); 20 }
threadPool.shutdown(); 21 } 22 }
输出结果:
pool-1-thread-2-task 1
pool-1-thread-1-task 0
pool-1-thread-3-task 2
pool-1-thread-2-task 3
pool-1-thread-1-task 4
pool-1-thread-2-task 6
pool-1-thread-3-task 5
pool-1-thread-2-task 8
pool-1-thread-1-task 7
pool-1-thread-3-task 9
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步