Java多线程之ThreadPool

本文详细介绍了Java中线程池的多种使用方式,包括普通线程池、定时线程池、带返回值的线程池等,并通过实例展示了如何创建线程池、提交任务以及获取结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里演示了普通线程池以及带有返回值的线程池的使用方式

  1. package com.jadyer.thread.pool;  
  2.   
  3. import java.util.Random;  
  4. import java.util.concurrent.Callable;  
  5. import java.util.concurrent.CompletionService;  
  6. import java.util.concurrent.ExecutionException;  
  7. import java.util.concurrent.ExecutorCompletionService;  
  8. import java.util.concurrent.ExecutorService;  
  9. import java.util.concurrent.Executors;  
  10. import java.util.concurrent.Future;  
  11. import java.util.concurrent.TimeUnit;  
  12.   
  13.   
  14. public class ThreadPoolTest  
  15.     public static void main(String[] args)  
  16.         new ThreadPoolTest().threadPoolTest();  
  17.         new ThreadPoolTest().threadPoolScheduledTest();  
  18.         new ThreadPoolTest().threadPoolCallbaleAndFutureSignTest();  
  19.         new ThreadPoolTest().threadPoolCallbaleAndFutureMoreTest();  
  20.      
  21.       
  22.       
  23.     public void threadPoolTest(){  
  24.         //newSingleThreadExecutor()的好处就是,若池中的线程死了,它会把一个"替补的线程"扶上位,即它会保证池中始终有一个线程存在   
  25.         ExecutorService threadPool Executors.newSingleThreadExecutor();  
  26.         for(int i=1i<=10i++)  
  27.             final int task i;  
  28.             threadPool.execute(new MyThread(task)); //注意execute()的返回值是void   
  29.          
  30.         System.out.println("all of 10 tasks have committed......");  
  31.           
  32.         //线程池中的任务均执行完毕后,关闭线程池   
  33.         threadPool.shutdown();  
  34.      
  35.       
  36.       
  37.     public void threadPoolScheduledTest(){  
  38.         //10秒后自动执行一次   
  39.         //Executors.newScheduledThreadPool(3).schedule(new MyScheduledThread(), 10, TimeUnit.SECONDS);   
  40.         //6秒后首次执行,之后每2秒均自动执行一次   
  41.         Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new MyScheduledThread(), 62TimeUnit.SECONDS);  
  42.      
  43.       
  44.       
  45.     public void threadPoolCallbaleAndFutureSignTest(){  
  46.         ExecutorService threadPool  Executors.newSingleThreadExecutor();  
  47.         Future<String> future threadPool.submit(  
  48.             new Callable<String>()  
  49.                 @Override  
  50.                 public String call() throws Exception  
  51.                     Thread.sleep(2000);  
  52.                     return "张起灵" 
  53.                 };  
  54.              
  55.         );  
  56.         System.out.println("等待结果");  
  57.         try  
  58.             System.out.println("拿到结果:" future.get()); //future.get(4, TimeUnit.SECONDS)   
  59.         catch (InterruptedException e)  
  60.             e.printStackTrace();  
  61.         catch (ExecutionException e)  
  62.             e.printStackTrace();  
  63.          
  64.      
  65.       
  66.       
  67.     public void threadPoolCallbaleAndFutureMoreTest(){  
  68.         ExecutorService threadPool  Executors.newFixedThreadPool(5);  
  69.         CompletionService<Integer> completionService new ExecutorCompletionService<Integer>(threadPool);  
  70.         for(int i=1i<=5i++){  
  71.             final int taskCode i;  
  72.             completionService.submit(  
  73.                 new Callable<Integer>(){  
  74.                     @Override  
  75.                     public Integer call() throws Exception  
  76.                         Thread.sleep(new Random().nextInt(5000));  
  77.                         return taskCode;  
  78.                      
  79.                  
  80.             );  
  81.          
  82.         for(int i=0i<5i++){  
  83.             try  
  84.                 System.out.println(completionService.take().get());  
  85.             catch (InterruptedException e)  
  86.                 e.printStackTrace();  
  87.             catch (ExecutionException e)  
  88.                 e.printStackTrace();  
  89.              
  90.          
  91.      
  92.  
  93.   
  94.   
  95. class MyThread implements Runnable{  
  96.     private Integer task;  
  97.     public MyThread(Integer task){  
  98.         this.task task;  
  99.      
  100.     @Override  
  101.     public void run()  
  102.         //这里不需要写成j,因为它和threadPoolTest()里面的for()循环中的i并不是同一个方法中的变量,故其不会冲突   
  103.         for(int i=1i<=10i++)  
  104.             try  
  105.                 Thread.sleep(20);  
  106.             catch (InterruptedException e)  
  107.                 e.printStackTrace();  
  108.              
  109.             System.out.println(Thread.currentThread().getName() is looping of " for  task of " task);  
  110.          
  111.      
  112.  
  113.   
  114.   
  115. class MyScheduledThread implements Runnable{  
  116.     @Override  
  117.     public void run()  
  118.         System.out.println("bombing......");  
  119.      
  120. }  

原文链接: http://blog.youkuaiyun.com/hopezhangbo/article/details/7383791
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值