Java并发编程中使用Executors类创建和管理线程的用法

1. 类 Executors
Executors类可以看做一个“工具类”。援引JDK1.6 API中的介绍:
  此包中所定义的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 类的工厂和实用方法。此类支持以下各种方法:
(1)创建并返回设置有常用配置字符串的 ExecutorService 的方法。
(2)创建并返回设置有常用配置字符串的 ScheduledExecutorService 的方法。
(3)创建并返回“包装的”ExecutorService 方法,它通过使特定于实现的方法不可访问来禁用重新配置。
(4)创建并返回 ThreadFactory 的方法,它可将新创建的线程设置为已知的状态。
(5)创建并返回非闭包形式的 Callable 的方法,这样可将其用于需要 Callable 的执行方法中。
    通过这个类能够获得多种线程池的实例,例如可以调用newSingleThreadExecutor()获得单线程的ExecutorService,调 用newFixedThreadPool()获得固定大小线程池的ExecutorService,等等。拿到ExecutorService可以做的事情就比 较多了,最简单的是用它来执行Runnable对象,也可以执行一些实现了Callable<T>的对象。用Thread的start()方 法没有返回值,如果该线程执行的方法有返回值那用ExecutorService就再好不过了,可以选择submit()、invokeAll()或者 invokeAny(),根据具体情况选择合适的方法即可。
此类中提供的一些方法有:
1.1 public static ExecutorService newCachedThreadPool()
创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。
 
1.2 public static ExecutorService newFixedThreadPool(int nThreads)
创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
 
1.3 public static ExecutorService newSingleThreadExecutor()
创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。
 
这三个方法都可以配合接口ThreadFactory的实例一起使用。并且返回一个ExecutorService接口的实例。
2. 接口 ThreadFactory
根据需要创建新线程的对象。使用线程工厂就无需再手工编写对 new Thread 的调用了,从而允许应用程序使用特殊的线程子类、属性等等。
此接口最简单的实现就是:

class SimpleThreadFactory implements ThreadFactory {
  public Thread newThread(Runnable r) {
   return new Thread(r);
  }
 }

3. 接口ExecutorService
该接口提供了管理终止的方法。
4.创建标准线程池启动线程
4.1 提供一个简单的实现Runnable接口的线程
MyThread.java

package com.zj.concurrency.executors;

public class MyThread implements Runnable {
  private int count = 1, number;

  public MyThread(int num) {
    number = num;
    System.out.println("Create Thread-" + number);
  }

  public void run() {
    while (true) {
      System.out.println("Thread-" + number + " run " + count+" time(s)");
      if (++count == 3)
       return;
    }
  }
}

这个线程会打印出相应的创建和执行信息。
 
4.2使用CachedThreadPool启动线程
CachedThreadPool.java

package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPool {
  public static void main(String[] args) {
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++)
      exec.execute(new MyThread(i));
    exec.shutdown();
  }
}

结果:

Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Create Thread-4
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)

4.3 使用FixedThreadPool启动线程

FixedThreadPool.java
package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPool {
  public static void main(String[] args) {
    ExecutorService exec = Executors.newFixedThreadPool(2);
    for (int i = 0; i < 5; i++)
      exec.execute(new MyThread(i));
    exec.shutdown();
  }
}

结果:

Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Create Thread-4
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)

 
4.4 使用SingleThreadExecutor启动线程
SingleThreadExecutor.java

package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SingleThreadExecutor {
  public static void main(String[] args) {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 5; i++)
      exec.execute(new MyThread(i));
    exec.shutdown();
  }
}

结果:

Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Create Thread-4
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)

5.配合ThreadFactory接口的使用
我们试图给线程加入daemon和priority的属性设置。
5.1设置后台线程属性
DaemonThreadFactory.java

package com.zj.concurrency.executors.factory;
import java.util.concurrent.ThreadFactory;

public class DaemonThreadFactory implements ThreadFactory {
  public Thread newThread(Runnable r) {
    Thread t = new Thread(r);
    t.setDaemon(true);
    return t;
  }
}

5.2 设置优先级属性
最高优先级MaxPriorityThreadFactory.java

package com.zj.concurrency.executors.factory;
import java.util.concurrent.ThreadFactory;

public class MaxPriorityThreadFactory implements ThreadFactory {
  public Thread newThread(Runnable r) {
    Thread t = new Thread(r);
    t.setPriority(Thread.MAX_PRIORITY);
    return t;
  }
}

最低优先级MinPriorityThreadFactory.java

package com.zj.concurrency.executors.factory;
import java.util.concurrent.ThreadFactory;

public class MinPriorityThreadFactory implements ThreadFactory {
  public Thread newThread(Runnable r) {
    Thread t = new Thread(r);
    t.setPriority(Thread.MIN_PRIORITY);
    return t;
  }
}

5.3启动带有属性设置的线程
ExecFromFactory.java

package com.zj.concurrency.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.zj.concurrency.executors.factory.DaemonThreadFactory;
import com.zj.concurrency.executors.factory.MaxPriorityThreadFactory;
import com.zj.concurrency.executors.factory.MinPriorityThreadFactory;

public class ExecFromFactory {
  public static void main(String[] args) throws Exception {
    ExecutorService defaultExec = Executors.newCachedThreadPool();
    ExecutorService daemonExec = Executors
       .newCachedThreadPool(new DaemonThreadFactory());
    ExecutorService maxPriorityExec = Executors
       .newCachedThreadPool(new MaxPriorityThreadFactory());
    ExecutorService minPriorityExec = Executors
       .newCachedThreadPool(new MinPriorityThreadFactory());
    for (int i = 0; i < 10; i++)
      daemonExec.execute(new MyThread(i));
    for (int i = 10; i < 20; i++)
      if (i == 10)
       maxPriorityExec.execute(new MyThread(i));
      else if (i == 11)
       minPriorityExec.execute(new MyThread(i));
      else
       defaultExec.execute(new MyThread(i));
  }
}

结果:

Create Thread-0
Create Thread-1
Create Thread-2
Create Thread-3
Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Create Thread-4
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)
Create Thread-5
Thread-5 run 1 time(s)
Thread-5 run 2 time(s)
Create Thread-6
Create Thread-7
Thread-7 run 1 time(s)
Thread-7 run 2 time(s)
Create Thread-8
Thread-8 run 1 time(s)
Thread-8 run 2 time(s)
Create Thread-9
Create Thread-10
Thread-10 run 1 time(s)
Thread-10 run 2 time(s)
Create Thread-11
Thread-9 run 1 time(s)
Thread-9 run 2 time(s)
Thread-6 run 1 time(s)
Thread-6 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Create Thread-12
Create Thread-13
Create Thread-14
Thread-12 run 1 time(s)
Thread-12 run 2 time(s)
Thread-13 run 1 time(s)
Thread-13 run 2 time(s)
Create Thread-15
Thread-15 run 1 time(s)
Thread-15 run 2 time(s)
Create Thread-16
Thread-16 run 1 time(s)
Thread-16 run 2 time(s)
Create Thread-17
Create Thread-18
Create Thread-19
Thread-14 run 1 time(s)
Thread-14 run 2 time(s)
Thread-17 run 1 time(s)
Thread-17 run 2 time(s)
Thread-18 run 1 time(s)
Thread-18 run 2 time(s)
Thread-19 run 1 time(s)
Thread-19 run 2 time(s)
Thread-11 run 1 time(s)
Thread-11 run 2 time(s)
(0)

相关推荐

  • Java 线程池ExecutorService详解及实例代码

    Java 线程池ExecutorService 1.线程池 1.1什么情况下使用线程池 单个任务处理的时间比较短. 将需处理的任务的数量大. 1.2使用线程池的好处 减少在创建和销毁线程上所花的时间以及系统资源的开销. 如果不使用线程池,有可能造成系统创建大量线程而导致消耗系统内存以及"过度切换"; 2.ExecutorService和Executors 2.1简介 ExecutorService是一个接口,继承了Executor, public interface ExecutorS

  • Java中Executor接口用法总结

    本文实例讲述了Java中Executor接口用法.分享给大家供大家参考.具体如下: 1.Java中Executor接口的定义 public interface Executor { void execute(Runnable command); } 2.Executors以下静态工厂方法创建一个线程池: a) newFixedThreadPool:创建一个定长的线程池.达到最大线程数后,线程数不再增长. 如果一个线程由于非预期Exception而结束,线程池会补充一个新的线程. b) newCa

  • 详解Java利用ExecutorService实现同步执行大量线程

    自从java1.5以后,官网就推出了Executor这样一个类,这个类,可以维护我们的大量线程在操作临界资源时的稳定性. 先上一段代码吧: TestRunnable.java public class TestRunnable implements Runnable { private String name; public TestRunnable(String name) { this.name = name; } @Override public void run() { while (t

  • java ThreadPoolExecutor 并发调用实例详解

    java ThreadPoolExecutor 并发调用实例详解 概述 通常为了提供任务的处理速度,会使用一些并发模型,ThreadPoolExecutor中的invokeAll便是一种. 代码 package test.current; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util

  • java中Executor,ExecutorService,ThreadPoolExecutor详解

    java中Executor,ExecutorService,ThreadPoolExecutor详解 1.Excutor 源码非常简单,只有一个execute(Runnable command)回调接口 public interface Executor { /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thre

  • java ThreadPoolExecutor使用方法简单介绍

    java  ThreadPoolExecutor 前言: 在项目中如果使用发短信这个功能,一般会把发短信这个动作变成异步的,因为大部分情况下,短信到底是发送成功或者失败,都不能影响主流程.当然像发送MQ消息等操作也是可以封装成异步操作的. 使用基本的New Thread 如果想一个操作变成异步的,可以直接new thread,然后在run方法中实现业务操作即可.例如: new Thread(new Runnable() { public void run() { //发短信.发MQ消息等 } }

  • java多线程并发executorservice(任务调度)类

    复制代码 代码如下: package com.yao; import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit; /** * 以下是一个带方法的类,它设置了 ScheduledExecutorService ,2

  • 理解java多线程中ExecutorService使用

    java.util.concurrent包里提供了关于多线程操作的类,平常用的比较多的是ExecutorService及其实现类(如ThreadPoolExecutor等),Executor,Executors,Future,Callable等 1. ExecutorService(继承自Executor)接口:提供了一些异步的多线程操作方法,如execute(), submit(), shutdown(), shutdownNow()等 2. Executor接口:执行提交的任务(线程),只有

  • Java Executor 框架的实例详解

    Java Executor 框架的实例详解 大多数并发都是通过任务执行的方式来实现的. 一般有两种方式执行任务:串行和并行. class SingleThreadWebServer { public static void main(String[] args) throws Exception { ServerSocket socket = new ServerSocket(80); while(true) { Socket conn = socket.accept(); handleRequ

  • java ExecutorService使用方法详解

    下面的例子主要讨论两个问题: 问题1.线程池固定大小,假设为5.那么向线程池放入10个线程,运行效果如何?其他线程的状态? 问题2.那么如何从线程池中移除某一个线程,确切说是使某一个线程成为空闲线程? 例子: package com.dada.executorService; import java.util.concurrent.TimeUnit; public class JobThread extends Thread { // 为线程命名 public JobThread(String

  • Java ThreadPoolExecutor的参数深入理解

    Java ThreadPoolExecutor的参数深入理解 一.使用Executors创建线程池    之前创建线程的时候都是用的Executors的newFixedThreadPool(),newSingleThreadExecutor(),newCachedThreadPool()这三个方法.当然Executors也是用不同的参数去new ThreadPoolExecutor     1. newFixedThreadPool() 创建线程数固定大小的线程池. 由于使用了LinkedBlo

  • java 中ThreadPoolExecutor原理分析

    java 中ThreadPoolExecutor原理分析 线程池简介 Java线程池是开发中常用的工具,当我们有异步.并行的任务要处理时,经常会用到线程池,或者在实现一个服务器时,也需要使用线程池来接收连接处理请求. 线程池使用 JDK中提供的线程池实现位于java.util.concurrent.ThreadPoolExecutor.在使用时,通常使用ExecutorService接口,它提供了submit,invokeAll,shutdown等通用的方法. 在线程池配置方面,Executor

随机推荐