package com.newer.cn; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test1 { public static void main(String[] args) { // 创建线程池的方式 // 创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程,在需要时使用提供的 ThreadFactory 创建新线程。 ExecutorService pool = Executors.newFixedThreadPool(5); // 创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。 ExecutorService pool1 = Executors.newSingleThreadExecutor(); // 创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。 ExecutorService pool2 = Executors.newCachedThreadPool(); //创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。 ExecutorService pool3 = Executors.newScheduledThreadPool(3); } }
举个例子
package com.newer.cn; public class Demo implements Runnable { @Override public void run() { String name = Thread.currentThread().getName(); System.out.println("执行当前线程的是:"+name); for(int i = 1;i <= 10;i++){ System.out.println(name+":"+i); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("执行任务完毕"); } }
package com.newer.cn; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for(int i = 1;i <= 5;i++){ Demo demo = new Demo(); cachedThreadPool.execute(demo); } } }
时间: 2024-10-26 16:51:58