`

ExecutorService与Executors例子的简单剖析

阅读更多
对于多线程有了一点了解之后,那么来看看java.lang.concurrent包下面的一些东西。在此之前,我们运行一个线程都是显式调用了Thread的start()方法。我们用concurrent下面的类来实现一下线程的运行,而且这将成为以后常用的方法或者实现思路。 

        看一个简单的例子: 

Java代码  
public class CacheThreadPool {   
    public static void main(String[] args) {   
        ExecutorService exec=Executors.newCachedThreadPool();   
        for(int i=0;i<5;i++)   
            exec.execute(new LiftOff());   
        exec.shutdown();//并不是终止线程的运行,而是禁止在这个Executor中添加新的任务   
    }   
}   


        这个例子其实很容易看懂,ExecutorService中有一个execute方法,这个方法的参数是Runnable类型。也就是说,将一个实现了Runnable类型的类的实例作为参数传入execute方法并执行,那么线程就相应的执行了。 

        一、ExecutorService 
        先看看ExecutorService,这是一个接口,简单的列一下这个接口: 

Java代码  
public interface ExecutorService extends Executor {   
   
    void shutdown();   
   
    List<Runnable> shutdownNow();   
   
    boolean isShutdown();   
   
    boolean isTerminated();   
   
    boolean awaitTermination(long timeout, TimeUnit unit)   
   
    <T> Future<T> submit(Callable<T> task);   
   
    <T> Future<T> submit(Runnable task, T result);   
   
    Future<?> submit(Runnable task);   
   
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)   
   
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)   
   
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)   
   
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,   
                    long timeout, TimeUnit unit)   
}   


        ExecuteService继承了Executor,Executor也是一个接口,里面只有一个方法: 

Java代码  
void execute(Runnable command)   



        二、Executors 
        Executors是一个类,直接援引JDK文档的说明来说一下这个类的作用: 
       

        Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods: 
 

        
Methods that create and return an ExecutorService set up with commonly useful configuration settings.         
Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.         
Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.         
Methods that create and return a ThreadFactory that sets newly created threads to a known state.         
Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable.        

        在上面的例子中,我们用到了newCachedThreadPool()方法。看一下这个方法: 

Java代码  
public static ExecutorService newCachedThreadPool() {   
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,   
                                      60L, TimeUnit.SECONDS,   
                                      new SynchronousQueue<Runnable>());   
    }   


        在源码中我们可以知道两点,1、这个方法返回类型是ExecutorService;2、此方法返回值实际是另一个类的实例。看一下这个类的信息: 

Java代码  
public class ThreadPoolExecutor extends AbstractExecutorService {   
    ..........   
    private final BlockingQueue<Runnable> workQueue;//这个变量在下面会提到   
    ..........   
}   


        ThreadPoolExecutor继承了AbstractExecutorService,而AbstractExecutorService又实现了ExecutorService接口。所以,根据多态,ThreadPoolExecutor可以看作是ExecutorService类型。 

        线程执行的最关键的一步是执行了executor方法,根据java的动态绑定,实际执行的是ThreadPoolExecutor所实现的executor方法。看看源码: 

Java代码  
public class ThreadPoolExecutor extends AbstractExecutorService {   
    ..........   
    public void execute(Runnable command) {   
        if (command == null)   
            throw new NullPointerException();   
        if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {   
            if (runState == RUNNING && workQueue.offer(command)) {   
                if (runState != RUNNING || poolSize == 0)   
                    ensureQueuedTaskHandled(command);   
            }   
            else if (!addIfUnderMaximumPoolSize(command))   
                reject(command); // is shutdown or saturated   
        }   
    }   
    ..........   
}   


        根据程序正常执行的路线来看,这个方法中比较重要的两个地方分别是: 
        1、workQueue.offer(command) 
        workQueue在上面提到过,是BlockingQueue<Runnable>类型的变量,这条语句就是将Runnable类型的实例加入到队列中。 
        2、ensureQueuedTaskHandled(command) 
        这个是线程执行的关键语句。看看它的源码: 

Java代码  
public class ThreadPoolExecutor extends AbstractExecutorService {   
    ..........   
    private void ensureQueuedTaskHandled(Runnable command) {   
        final ReentrantLock mainLock = this.mainLock;   
        mainLock.lock();   
        boolean reject = false;   
        Thread t = null;   
        try {   
            int state = runState;   
            if (state != RUNNING && workQueue.remove(command))   
                reject = true;   
            else if (state < STOP &&   
                     poolSize < Math.max(corePoolSize, 1) &&   
                     !workQueue.isEmpty())   
                t = addThread(null);   
        } finally {   
            mainLock.unlock();   
        }   
        if (reject)   
            reject(command);   
        else if (t != null)   
            t.start();   
    }   
    ..........   
}   


        在这里我们就可以看到最终执行了t.start()方法来运行线程。在这之前的重点是t=addThread(null)方法,看看addThread方法的源码: 

Java代码  
public class ThreadPoolExecutor extends AbstractExecutorService {   
    ..........   
    private Thread addThread(Runnable firstTask) {   
        Worker w = new Worker(firstTask);   
        Thread t = threadFactory.newThread(w);   
        if (t != null) {   
            w.thread = t;   
            workers.add(w);   
            int nt = ++poolSize;   
            if (nt > largestPoolSize)   
                largestPoolSize = nt;   
        }   
        return t;   
    }   
    ..........   
}   


        这里两个重点,很明显: 
        1、Worker w = new Worker(firstTask) 
        2、Thread t = threadFactory.newThread(w) 
        先看Worker是个什么结构: 

Java代码  
public class ThreadPoolExecutor extends AbstractExecutorService {   
    ..........   
    private final class Worker implements Runnable {   
        ..........   
        Worker(Runnable firstTask) {   
            this.firstTask = firstTask;   
        }   
   
        private Runnable firstTask;   
        ..........   
   
        public void run() {   
            try {   
                Runnable task = firstTask;   
                firstTask = null;   
                while (task != null || (task = getTask()) != null) {   
                    runTask(task);   
                    task = null;   
                }   
            } finally {   
                workerDone(this);   
            }   
        }   
    }   
   
    Runnable getTask() {   
        for (;;) {   
            try {   
                int state = runState;   
                if (state > SHUTDOWN)   
                    return null;   
                Runnable r;   
                if (state == SHUTDOWN)  // Help drain queue   
                    r = workQueue.poll();   
                else if (poolSize > corePoolSize || allowCoreThreadTimeOut)   
                    r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS);   
                else   
                    r = workQueue.take();   
                if (r != null)   
                    return r;   
                if (workerCanExit()) {   
                    if (runState >= SHUTDOWN) // Wake up others   
                        interruptIdleWorkers();   
                    return null;   
                }   
                // Else retry   
            } catch (InterruptedException ie) {   
                // On interruption, re-check runState   
            }   
        }   
    }   
    }   
    ..........   
}   


        Worker是一个内部类。根据之前可以知道,传入addThread的参数是null,也就是说Work中firstTask为null。
        在看看newThread是一个什么方法: 

Java代码  
public class Executors {   
    ..........   
    static class DefaultThreadFactory implements ThreadFactory {   
        ..........   
        public Thread newThread(Runnable r) {   
            Thread t = new Thread(group, r,   
                                  namePrefix + threadNumber.getAndIncrement(),   
                                  0);   
            if (t.isDaemon())   
                t.setDaemon(false);   
            if (t.getPriority() != Thread.NORM_PRIORITY)   
                t.setPriority(Thread.NORM_PRIORITY);   
            return t;   
        }   
        ..........   
    }   
    ..........   
}   


        通过源码可以得知threadFactory的实际类型是DefaultThreadFactory,而DefaultThreadFactory是Executors的一个嵌套内部类。 

        之前我们提到了t.start()这个方法执行了线程。那么现在从头顺一下,看看到底是执行了谁的run方法。首先知道,t=addThread(null),而addThread内部执行了下面三步,Worker w = new Worker(null);Thread t = threadFactory.newThread(w);return t;这里两个t是一致的。 
        从这里可以看出,t.start()实际上执行的是Worker内部的run方法。run()内部会在if条件里面使用“短路”:判断firstTask是否为null,若不是null则直接执行firstTask的run方法;如果是null,则调用getTask()方法来获取Runnable类型实例。从哪里获取呢?workQueue!在execute方法中,执行ensureQueuedTaskHandled(command)之前就已经把Runnable类型实例放入到workQueue中了,所以这里可以从workQueue中获取到。


分享到:
评论

相关推荐

    Java+创建线程的例子源代码学习

    `ExecutorService`通常与`ThreadPoolExecutor`或`Executors`类一起使用,如以下示例所示: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class MyTask ...

    多线程读取文件

    this.executorService = Executors.newFixedThreadPool(numThreads); } public String read() throws IOException, InterruptedException, ExecutionException { List&lt;Future&lt;String&gt;&gt; futures = new ArrayList...

    socket实例

    executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE); System.out.println(""); } ``` - **service 方法**:循环监听客户端连接请求,接受连接后将每个...

    Java 5_0 多线程编程实践

    以下是一个简单的示例,演示如何使用`ExecutorService`和`Callable`/`Future`来实现服务器端处理客户端请求的功能: ```java private static final int PORT = 19527; ServerSocket serverListenSocket = new ...

    android异步操作例子

    在Android开发中,异步操作是至关重要的,它能让应用程序在执行耗时任务时保持界面...这个"AysncTest"例子可能就是一个演示这些异步处理技术的简单应用,通过分析和学习,开发者可以更好地掌握Android异步编程的精髓。

    TaskthreadDemo2.rar_java programming

    ExecutorService executor = Executors.newFixedThreadPool(5); Future&lt;?&gt; future = executor.submit(new TaskthreadDemo2()); // future.get()用于获取任务结果,如果任务已完成 executor.shutdown(); // 关闭...

    多线程实例片段

    ExecutorService executor = Executors.newFixedThreadPool(5); executor.execute(new MyTask()); // 提交任务到线程池 executor.shutdown(); // 关闭线程池 ``` 在实际开发中,工具库如Apache Commons Lang的`...

    Android 文件下载功能Java多线程下载功能的例子实例源码

    3. 使用ExecutorService:Java并发框架的一部分,它允许我们创建线程池,管理和控制线程的生命周期。例如,使用Executors.newFixedThreadPool(int nThreads)创建固定大小的线程池。 三、多线程下载原理 多线程下载...

    基于socket java 语言网络通讯机制和程序设计

    ExecutorService executor = Executors.newFixedThreadPool(maxThreads); while (true) { // 接受客户端连接 Socket clientSocket = serverSocket.accept(); // 创建处理线程 Runnable worker = new ...

    Android源码设计模式解析与实战》

    ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); public ImageLoader() { initImageCache(); } private void initImageCache() { final ...

    Java组合式异步编程方法详解.pdf

    ExecutorService executor = Executors.newCachedThreadPool(); Future&lt;Double&gt; future = executor.submit(new Callable() { public Double call() { return doSomeLongComputation(); } }); doSomethingElse(); ...

    多线程java买票系统

    在这个例子中,可能使用了`Executors`工具类来创建一个线程池,例如`Executors.newFixedThreadPool(int nThreads)`,创建一个固定大小的线程池,可以处理多个并发请求。 4. **`saleTicket.java`** 这个文件可能...

    2dloop2darray_pl_multest.7z

    ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (int i = 0; i ; i++) { executor.submit(() -&gt; { for (int j = 0; j ; j++) { // 对matrix[i][j]进行操作 } }); } executor....

    Java 多线程与并发编程总结.doc

    `ExecutorService`是线程池的接口,可以使用`Executors`工厂类创建不同类型的线程池,如固定大小线程池、可缓存线程池、单线程线程池等。 总之,Java多线程与并发编程是Java程序员必须掌握的核心技能,它涉及到操作...

    深入java线程池的使用详解

    使用`Executors`创建线程池的例子: ```java ExecutorService executor = Executors.newFixedThreadPool(5); // 创建一个包含5个线程的线程池 executor.execute(new Runnable() { @Override public void run() { ...

    JAVA中锁的解决方案.docx

    ExecutorService es = Executors.newFixedThreadPool(50); // 闭锁 CountDownLatch cdl = new CountDownLatch(5000); for (int i = 0; i ; i++) { es.execute(() -&gt; { test.increment(); cdl.countDown(); }...

    Java多线程饥饿与公平介绍及代码示例

    ExecutorService exec = Executors.newSingleThreadScheduledExecutor(); // ExecutorService exec = Executors.newCachedThreadPool(); //如果添加给线程池中添加足够多的线程,就可以让所有任务都执行,避免...

    Java Lambda 编程之道

    ExecutorService executor = Executors.newFixedThreadPool(5); executor.submit(() -&gt; { // 执行异步任务 System.out.println("Task executed in thread: " + Thread.currentThread().getName()); }); ``` 这里...

    java callable(多线程)

    ExecutorService es = Executors.newFixedThreadPool(3); try { Future&lt;String&gt; future1 = es.submit(new MyCallableClass(0)); System.out.println("task1:" + future1.get()); Future&lt;String&gt; future2 = es....

Global site tag (gtag.js) - Google Analytics