摘要:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, //使用一个基于FIFO排序的阻塞队列,在所有corePoolSize线程都忙时新任务将在队列中等待 new LinkedBlockingQueue<Runnable>());}
1 public class HeartBeat { 2 public static void main(String[] args) { 3 ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); 4 Runnable task = new Runnable() { 5 public void run() { 6 System.out.println("HeartBeat........................."); 7 } 8 }; 9 executor.scheduleAtFixedRate(task,5,3, TimeUnit.SECONDS); //5秒后第一次执行,之后每隔3秒执行一次10 }11 }
HeartBeat....................... //5秒后第一次输出HeartBeat....................... //每隔3秒输出一个
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, //使用同步队列,将任务直接提交给线程 new SynchronousQueue<Runnable>());}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class ThreadPoolTest { public static void main(String[] args) throws InterruptedException { ExecutorService threadPool = Executors.newCachedThreadPool(); //线程池里面的线程数会动态变化,并可在线程线被移除前重用 for ( int i = 1 ; i <= 3 ; i ++) { final int task = i; //10个任务 //TimeUnit.SECONDS.sleep(1); threadPool.execute( new Runnable() { //接受一个Runnable实例 public void run() { System.out.println( "线程名字: " + Thread.currentThread().getName() + " 任务名为: " +task); } }); } } } |
线程名字: pool-1-thread-1 任务名为: 1线程名字: pool-1-thread-2 任务名为: 2线程名字: pool-1-thread-3 任务名为: 3
线程名字: pool-1-thread-1 任务名为: 1线程名字: pool-1-thread-1 任务名为: 2线程名字: pool-1-thread-1 任务名为: 3
1 2 3 4 5 6 7 8 9 10 11 | public class CallableAndFuture { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit( new Callable<String>() { //接受一上callable实例 public String call() throws Exception { return "MOBIN" ; } }); System.out.println( "任务的执行结果:" +future.get()); } } |
任务的执行结果:MOBIN
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class CompletionServiceTest { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool( 10 ); //创建含10.条线程的线程池 CompletionService completionService = new ExecutorCompletionService(executor); for ( int i = 1 ; i <= 10 ; i ++) { final int result = i; completionService.submit( new Callable() { public Object call() throws Exception { Thread.sleep( new Random().nextInt( 5000 )); //让当前线程随机休眠一段时间 return result; } }); } System.out.println(completionService.take().get()); //获取执行结果 } } |
3
联系客服