一个比较简单的 newFixedThreadPool多线程实现

61、编写多线程程序有几种实现方式?

答:Java 5以前实现多线程有两种实现方法:一种是继承Thread类;另一种是实现Runnable接口。两种方式都要通过重写run()方法来定义线程的行为,推荐使用后者,因为Java中的继承是单继承,一个类有一个父类,如果继承了Thread类就无法再继承其他类了,显然使用Runnable接口更为灵活。

补充:Java 5以后创建线程还有第三种方式:实现Callable接口,该接口中的call方法可以在线程执行结束时产生一个返回值,代码如下所示:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.lovo.demo;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.concurrent.Callable;  
  6. import java.util.concurrent.ExecutorService;  
  7. import java.util.concurrent.Executors;  
  8. import java.util.concurrent.Future;  
  9.   
  10.   
  11. class MyTask implements Callable<Integer> {  
  12.     private int upperBounds;  
  13.       
  14.     public MyTask(int upperBounds) {  
  15.         this.upperBounds = upperBounds;  
  16.     }  
  17.       
  18.     @Override  
  19.     public Integer call() throws Exception {  
  20.         int sum = 0;   
  21.         for(int i = 1; i <= upperBounds; i++) {  
  22.             sum += i;  
  23.         }  
  24.         return sum;  
  25.     }  
  26.       
  27. }  
  28.   
  29. public class Test {  
  30.   
  31.     public static void main(String[] args) throws Exception {  
  32.         List<Future<Integer>> list = new ArrayList<>();  
  33.         ExecutorService service = Executors.newFixedThreadPool(10);  
  34.         for(int i = 0; i < 10; i++) {  
  35.             list.add(service.submit(new MyTask((int) (Math.random() * 100))));  
  36.         }  
  37.           
  38.         int sum = 0;  
  39.         for(Future<Integer> future : list) {  
  40.             while(!future.isDone()) ;  
  41.             sum += future.get();  
  42.         }  
  43.           
  44.         System.out.println(sum);  
  45.     }  
  46. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值