标签:style blog io ar sp for java strong on
Executors工具类,创建一个线程池,固定的线程池
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadAtomic { public static void main(String[] args) { //5个线程的线程池 ExecutorService threadPool = Executors.newFixedThreadPool(5); for(int j = 1;j<=10;j++){ final int task = j; threadPool.execute(new Runnable(){ public void run() { for(int i = 1;i<=10;i++){ try { Thread.sleep(30); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+ " is running "+i+" for task is "+ task); } } });//向池子中添加任务 } System.out.println("10 task is over"); } }
第二种:
缓存的线程池,简单说就是线程池中的线程个数不确定,当有3个任务的时候,池子中的线程就是3个,每个线程拿一个任务做,当任务减少
时,池子中的多余线程会被回收,总之,池子中的线程是动态的
ExecutorService threadPool = Executors.newCachedThreadPool();
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Executors.newScheduledThreadPool(3).schedule(new Runnable() { public void run() { System.out.println("ok!"); } }, 3, TimeUnit.SECONDS); //3秒后打印ok Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() { public void run() { System.out.println("ok!"); } }, 3,2, TimeUnit.SECONDS);
标签:style blog io ar sp for java strong on
原文地址:http://blog.csdn.net/wjw0130/article/details/41882275