zoukankan      html  css  js  c++  java
  • ExecutorService线程池管理

      1 public class inter {
      2     /**
      3      * 启动单个线程,顺序执行
      4      */
      5 
      6     public void SingleThread() {
      7         ExecutorService es = Executors.newSingleThreadExecutor();
      8         es.execute(new Runnable() {
      9             public void run() {
     10                 System.out.println("启动single线程="
     11                         + Thread.currentThread().getName());
     12             }
     13         });
     14         es.execute(new Runnable() {
     15 
     16             @Override
     17             public void run() {
     18                 System.out.println("再次启动single线程=="
     19                         + Thread.currentThread().getName());
     20             }
     21         });
     22     }
     23 
     24     /**
     25      * 根据任务量启动线程数量
     26      */
     27     public void AllThread() {
     28         ExecutorService es = Executors.newCachedThreadPool();
     29         for (int i = 0; i < 4; i++) {
     30             final int t = i;
     31             es.execute(new Runnable() {
     32 
     33                 @Override
     34                 public void run() {
     35                     while (true) {
     36                         System.out.println("当前线程是:"
     37                                 + Thread.currentThread().getName() + "当前 i :"
     38                                 + t);
     39                         try {
     40                             Thread.sleep(1000 * 60);
     41                         } catch (InterruptedException e) {
     42                             // TODO Auto-generated catch block
     43                             e.printStackTrace();
     44                         }
     45                     }
     46                 }
     47             });
     48         }
     49     }
     50 
     51     /**
     52      * 确定线程数量
     53      */
     54     public void FixedThread() {
     55         ExecutorService es = Executors.newFixedThreadPool(3);
     56         for (int i = 0; i < 4; i++) {
     57             final int t = i;
     58             es.execute(new Runnable() {
     59 
     60                 @Override
     61                 public void run() {
     62                     while (true) {
     63                         System.out.println("当前线程是:"
     64                                 + Thread.currentThread().getName() + "当前 i :"
     65                                 + t);
     66                         try {
     67                             Thread.sleep(1000 * 3);
     68                         } catch (InterruptedException e) {
     69                             // TODO Auto-generated catch block
     70                             e.printStackTrace();
     71                         }
     72                         if (2 == t) {
     73                             return;
     74                         }
     75                     }
     76                 }
     77             });
     78         }
     79     }
     80 
     81     /**
     82      * 带返回值的callback
     83      * 
     84      * @return
     85      * @throws InterruptedException
     86      * @throws ExecutionException
     87      */
     88     public String Call() throws InterruptedException, ExecutionException {
     89         ExecutorService es = Executors.newCachedThreadPool();
     90         ArrayList<Future<String>> future = new ArrayList<Future<String>>();
     91         for (int j = 0; j < 100; j++) {
     92             // 带着参数j去的,所以以后可以换成图片的地址什么的
     93             future.add(es.submit(new MyCall(j)));
     94         }
     95         System.out.println("ca");
     96         System.out.println(future.size());
     97         for (Future<String> fu : future) {
     98             System.out.println("返回值:" + fu.get());
     99         }
    100         return null;
    101 
    102     }
    103 
    104     // 用于获取返回值的
    105     class MyCall implements Callable<String> {
    106         private int sql;
    107 
    108         public MyCall(int i) {
    109             // TODO Auto-generated constructor stub
    110             this.sql = i;
    111         }
    112 
    113         @Override
    114         public String call() throws Exception {
    115             // TODO Auto-generated method stub
    116             System.out.println("执行" + sql + ","
    117                     + Thread.currentThread().getName());
    118             System.out.println("Weak Up" + sql);
    119             return "完成" + sql;
    120         }
    121 
    122     }
    123 }
     1 下面给出了一个网络服务的简单结构,这里线程池中的线程作为传入的请求。它使用了预先配置的 Executors.newFixedThreadPool(int) 工厂方法: 
     2  class NetworkService implements Runnable {
     3     private final ServerSocket serverSocket;
     4     private final ExecutorService pool;
     5 
     6     public NetworkService(int port, int poolSize)
     7         throws IOException {
     8       serverSocket = new ServerSocket(port);
     9       pool = Executors.newFixedThreadPool(poolSize);
    10     }
    11  
    12     public void run() { // run the service
    13       try {
    14         for (;;) {
    15           pool.execute(new Handler(serverSocket.accept()));
    16         }
    17       } catch (IOException ex) {
    18         pool.shutdown();
    19       }
    20     }
    21   }
    22 
    23   class Handler implements Runnable {
    24     private final Socket socket;
    25     Handler(Socket socket) { this.socket = socket; }
    26     public void run() {
    27       // read and service request on socket
    28     }
    29  }
     1 下列方法分两个阶段关闭 ExecutorService。第一阶段调用 shutdown 拒绝传入任务,然后调用 shutdownNow(如有必要)取消所有遗留的任务: 
     2  void shutdownAndAwaitTermination(ExecutorService pool) {
     3    pool.shutdown(); // Disable new tasks from being submitted
     4    try {
     5      // Wait a while for existing tasks to terminate
     6      if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
     7        pool.shutdownNow(); // Cancel currently executing tasks
     8        // Wait a while for tasks to respond to being cancelled
     9        if (!pool.awaitTermination(60, TimeUnit.SECONDS))
    10            System.err.println("Pool did not terminate");
    11      }
    12    } catch (InterruptedException ie) {
    13      // (Re-)Cancel if current thread also interrupted
    14      pool.shutdownNow();
    15      // Preserve interrupt status
    16      Thread.currentThread().interrupt();
    17    }
    18  }

    其中实现Runnable和Callable不同的是,前者没有返回值,后者有。

  • 相关阅读:
    关于size_t
    图的搜索算法之迷宫问题和棋盘马走日问题
    螺旋矩阵与螺旋队列
    内存分配问题
    质数的判断
    全局变量、静态全局变量、静态局部变量和局部变量的区别
    程序员必知之代码规范标准
    字符串查找与类型转换(C/C++)
    sizeof与strlen()的用法与区别
    关于C++的输入输出流(cin、sstream和cout)
  • 原文地址:https://www.cnblogs.com/qinghuaideren/p/3056819.html
Copyright © 2011-2022 走看看