多线程CompletionService接口之实现类ExecutorCompletionService

原有Future 对象获取任务的执行状态:

package com.thread;
 
/**
 * @author liuchj
 * @version 1.0
 * @className MyThreadTest
 * @description //TODO
 * @date 2019/5/29
 **/
 
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
 
public class ThreadPoolTask {
 
    /**
     * 线程安全的队列
     */
    static Queue<String> queue = new ConcurrentLinkedQueue<String>();
 
    static {
        //入队列
        for (int i = 0; i < 9; i++) {
            queue.add("task-" + i);
        }
    }
 
 
    public static void main(String[] args) {
        MyThreadFactory threadFactory = new MyThreadFactory();
        //线程池方式
        ExecutorService executor = new ThreadPoolExecutor(5, 5,
                10L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), threadFactory);
 
        List<Future<String>> futures = new ArrayList<Future<String>>(10);
 
        for (int i = 0; i < queue.size(); i++) {
            Future<String> future = executor.submit(new InnerThreadCallable());
            futures.add(future);
        }
 
        for (Future<String> future : futures) {
            try {
                String result = future.get();
                System.out.println("result = " + result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        //关闭线程池中所有线程
        executor.shutdown();
 
    }
}
 
 
/**
 * 线程:执行出队列任务的线程
 */
class InnerThreadCallable implements Callable<String> {
 
    @Override
    public String call() throws Exception {
        //出队列
        while (ThreadPoolTask.queue.size() > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = ThreadPoolTask.queue.poll();
            if (value != "" && null != value) {
                System.out.println("线程" + Thread.currentThread().getName() + " 执行了task: " + value);
            }
        }
        return "run";
    }
}
 
class MyThreadFactory implements ThreadFactory {
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;
 
    public MyThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
 
        namePrefix = "Thread-";
    }
 
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        return t;
    }
}
 

执行结果:

线程Thread-4 执行了task: task-0
线程Thread-3 执行了task: task-1
线程Thread-2 执行了task: task-2
线程Thread-1 执行了task: task-3
线程Thread-5 执行了task: task-4
线程Thread-4 执行了task: task-5
线程Thread-3 执行了task: task-6
线程Thread-1 执行了task: task-7
线程Thread-5 执行了task: task-8
result = run
result = run
result = run
result = run
result = run
result = run
result = run
result = run
result = run

这段代码稍微有点复杂,而且有不足的地方。如果第一个任务耗费非常长的时间来执行,然后其他的任务都早于它结束,那么当前线程就无法在第一个任务结束之前获得执行结果,但是别着急,Java 为你提供了解决方案——CompletionService。一个 CompletionService 就是一个服务,用以简化等待任务的执行结果,实现的类是 ExecutorCompletionService,该类基于 ExecutorService,因此我们可试试下面的代码。

 

使用ExecutorCompletionService之后,代码如下:

package com.thread;

/**
 * @author liuchj
 * @version 1.0
 * @className MyThreadTest
 * @description //TODO
 * @date 2019/5/29
 **/

import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolTask {

    /**
     * 线程安全的队列
     */
    static Queue<String> queue = new ConcurrentLinkedQueue<String>();

    static {
        //入队列
        for (int i = 0; i < 9; i++) {
            queue.add("task-" + i);
        }
    }

    public static void main(String[] args) {
        MyThreadFactory threadFactory = new MyThreadFactory();
        //线程池方式
        ExecutorService executor = new ThreadPoolExecutor(5, 5,
                10L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), threadFactory);
        CompletionService<String> pool = new ExecutorCompletionService<String>(executor);

        for (int i = 0; i < queue.size(); i++) {
            pool.submit(new InnerThreadCallable());
        }

        for (int i = 0; i < queue.size(); i++) {
            try {
                String result = pool.take().get();
                System.out.println("result = " + result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            //Compute the result
        }

        executor.shutdown();
    }
}

/**
 * 线程:执行出队列任务的线程
 */
class InnerThreadCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        //出队列
        while (ThreadPoolTask.queue.size() > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = ThreadPoolTask.queue.poll();
            if (value != "" && null != value) {
                System.out.println("线程" + Thread.currentThread().getName() + " 执行了task: " + value);
            }
        }
        return "run";
    }
}

class MyThreadFactory implements ThreadFactory {
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public MyThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        namePrefix = "Thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        return t;
    }
}

执行结果:

线程Thread-3 执行了task: task-0
线程Thread-4 执行了task: task-1
线程Thread-1 执行了task: task-2
线程Thread-2 执行了task: task-3
线程Thread-5 执行了task: task-4
线程Thread-4 执行了task: task-5
线程Thread-3 执行了task: task-6
线程Thread-5 执行了task: task-7
线程Thread-1 执行了task: task-8
result = run

通过这段代码,我们可以根据执行结束的顺序获取对应的结果,而无需维护一个 Future 对象的集合。这就是本文的全部,通过 Java 为我们提供的各种工具,可以方便的进行多任务的编程,通过使用 Executors、ExecutorService 以及 CompletionService 等工具类,我们可以创建复杂的并行任务执行算法,而且可以轻松改变线程数。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

痴书先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值