【Java多线程-4】CompletionService详解

 *        queue is treated as unbounded -- failed attempted

 *        {@code Queue.add} operations for completed tasks cause

 *        them not to be retrievable.

 * @throws NullPointerException if executor or completionQueue are {@code null}

 */

public ExecutorCompletionService(Executor executor,

                                 BlockingQueue<Future<V>> completionQueue) {

    if (executor == null || completionQueue == null)

        throw new NullPointerException();

    this.executor = executor;

    this.aes = (executor instanceof AbstractExecutorService) ?

        (AbstractExecutorService) executor : null;

    this.completionQueue = completionQueue;

}



这两个构造方法都需要传入一个线程池,如果不指定 completionQueue,那么默认会使用无界的 LinkedBlockingQueue。任务执行结果的 Future 对象就是加入到 completionQueue 中。



[]( )1.2 方法

-----------------------------------------------------------------



CompletionService 接口提供的方法有 5 个:



public interface CompletionService {

//提交线程任务

Future<V> submit(Callable<V> task);

//提交线程任务

Future<V> submit(Runnable task, V result);

//阻塞等待

Future<V> take() throws InterruptedException;

//非阻塞等待

Future<V> poll();

//带时间的非阻塞等待

Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException;

}




方法简介如下:



*   submit(Callable task):提交线程任务,交由 Executor 对象去执行,并将结果放入阻塞队列;

*   take():在阻塞队列中获取并移除一个元素,该方法是阻塞的,即获取不到的话线程会一直阻塞;

*   poll():在阻塞队列中获取并移除一个元素,该方法是非阻塞的,获取不到即返回 null ;

*   poll(long timeout, TimeUnit unit):从阻塞队列中非阻塞地获取并移除一个元素,在设置的超时时间内获取不到即返回 null ;



接下来,我们重点看一下submit 的源码:



public Future submit(Callable task) {

if (task == null) throw new NullPointerException();

RunnableFuture<V> f = newTaskFor(task);

executor.execute(new QueueingFuture(f));

return f;

}




从submit 方法的源码中可以确认两点:



1.  线程任务确实是由 Executor 对象执行的;

2.  提交某个任务时,该任务首先将被包装为一个QueueingFuture。



继续追查 QueueingFuture,可以发现:  

该类重写了 FutureTask 的done方法,当计算完成时,把Executor执行的计算结果放入BlockingQueue中,而放入结果是按任务完成顺序来进行的,即先完成的任务先放入阻塞队列。



/**

  • FutureTask extension to enqueue upon completion

*/

private class QueueingFuture extends FutureTask {

QueueingFuture(RunnableFuture<V> task) {  

    super(task, null);  

    this.task = task;  

}  

protected void done() { completionQueue.add(task); }  

private final Future<V> task;  

}




由此,CompletionService 实现了生产者提交任务和消费者获取结果的解耦,任务的完成顺序由 CompletionService 来保证,消费者一定是按照任务完成的先后顺序来获取执行结果。



[]( )2 CompletionService 使用示例

===================================================================================



下面我们使用一个小例子,领略一下 CompletionService 的便利:



import java.util.Date;

import java.util.concurrent.*;

/**

  • @author guozhengMu

  • @version 1.0

  • @date 2019/11/8 20:25

  • @description

  • @modify

*/

public class CompletionServiceTest {

public static void main(String[] args) {

    ExecutorService executor = Executors.newCachedThreadPool();

    CompletionService<String> cs = new ExecutorCompletionService<>(executor);

    // 此线程池运行5个线程

    for (int i = 0; i < 5; i++) {

        final int index = i;

        cs.submit(() -> {

            String name = Thread.currentThread().getName();

            System.out.println(name + " 启动:" + new Date());

            TimeUnit.SECONDS.sleep(10 - index * 2);

            return name;

        });

    }

    executor.shutdown();



    for (int i = 0; i < 5; i++) {

        try {

            System.out.println(cs.take().get() + " 结果:" + new Date());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

}




运行结果:



pool-1-thread-2 启动:Sun Nov 10 11:34:13 CST 2019

pool-1-thread-4 启动:Sun Nov 10 11:34:13 CST 2019

pool-1-thread-3 启动:Sun Nov 10 11:34:13 CST 2019

pool-1-thread-5 启动:Sun Nov 10 11:34:13 CST 2019

pool-1-thread-1 启动:Sun Nov 10 11:34:13 CST 2019

pool-1-thread-5 结果:Sun Nov 10 11:34:15 CST 2019

pool-1-thread-4 结果:Sun Nov 10 11:34:17 CST 2019

pool-1-thread-3 结果:Sun Nov 10 11:34:19 CST 2019

pool-1-thread-2 结果:Sun Nov 10 11:34:21 CST 2019

pool-1-thread-1 结果:Sun Nov 10 11:34:23 CST 2019




通过观察运行结果,可以看到,结果输出的顺序与线程任务执行完成的顺序一致。



[]( )3 完整源码

=================================================================



package java.util.concurrent;

public class ExecutorCompletionService implements CompletionService {

// 线程池

private final Executor executor;

private final AbstractExecutorService aes;

// 阻塞队列:存放线程执行结果

private final BlockingQueue<Future<V>> completionQueue;



//内部封装的一个用来执线程的FutureTask

private class QueueingFuture extends FutureTask<Void> {

    QueueingFuture(RunnableFuture<V> task) {

        super(task, null);

        this.task = task;

    }

    //线程执行完成后调用此函数将结果放入阻塞队列

    protected void done() { 

    	completionQueue.add(task); 

    }

    private final Future<V> task;

}



private RunnableFuture<V> newTaskFor(Callable<V> task) {

    if (aes == null)

本次面试答案,以及收集到的大厂必问面试题分享:

字节跳动超高难度三面java程序员面经,大厂的面试都这么变态吗?

}

    //线程执行完成后调用此函数将结果放入阻塞队列

    protected void done() { 

    	completionQueue.add(task); 

    }

    private final Future<V> task;

}



private RunnableFuture<V> newTaskFor(Callable<V> task) {

    if (aes == null)

本次面试答案,以及收集到的大厂必问面试题分享:

[外链图片转存中…(img-sJr2ZiBO-1714155619318)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

  • 11
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,您的问题是关于Java线程的存钱取钱问题。这是一个经典的多线程同步问题,可以通过使用synchronized关键字来实现线程安全。下面是一个简单的示例代码: ```java public class BankAccount { private int balance; public BankAccount(int balance) { this.balance = balance; } public synchronized void deposit(int amount) { balance += amount; System.out.println("Deposit successful. Balance: " + balance); } public synchronized void withdraw(int amount) { if (balance < amount) { System.out.println("Withdraw failed. Insufficient balance."); return; } balance -= amount; System.out.println("Withdraw successful. Balance: " + balance); } } public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(1000); // Create two threads to simulate deposit and withdraw Thread depositThread = new Thread(() -> { for (int i = 0; i < 5; i++) { account.deposit(100); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread withdrawThread = new Thread(() -> { for (int i = 0; i < 5; i++) { account.withdraw(200); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); depositThread.start(); withdrawThread.start(); } } ``` 在这个示例代码中,我们创建了一个银行账户类BankAccount,并在其中实现了deposit和withdraw方法,并使用synchronized关键字来保证线程安全。 在main方法中,我们创建了两个线程来模拟存款和取款操作,每个线程执行5次操作。我们使用Thread.sleep方法来模拟每个操作之间的间隔,以便更好地观察多线程操作的结果。 当多个线程同时访问BankAccount对象的deposit和withdraw方法时,synchronized关键字可以确保每个方法只能被一个线程访问,从而避免了竞争条件和数据不一致的问题。 希望这个示例代码能够回答您的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值