gpt4 book ai didi

java - Java 设计模式 : Does this look familiar to anyone?

转载 作者:行者123 更新时间:2023-11-30 06:39:39 24 4
gpt4 key购买 nike

在我的应用程序中,我有以下重复出现的模式,我觉得这是一些我不知道的常见模式的不完整或扭曲版本。在我的实现中,我似乎找不到实现特定操作的好方法,如下所述。

对象的集合,我们称它们为“源”,如果您对它们调用方法,就会生成数据。 ScheduledThreadPoolExecutor 的实例(来自 <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html" rel="noreferrer noopener nofollow">java.util.concurrent</a> )用于定期读取源并将数据放在公共(public)出站队列中:

--o      method calls    +-----+--o       <--         |  o  |     --->    |||||||||||          -->         | o o |--o      data         +-----+sources             thread pool          outbound queue

The sources, the thread pool and the queue are members of a class that provides methods to add sources and to retrieve the head of the queue.

Below is the code to add a new source. I'm wondering what happens if I remove a source from the collection.

public void vAddSource(ISource src)
{
this._rgSources.add(src);
final ISource srcT = src;
// q is the outbound queue, which is a private member in the class
// defining this method. Name is abbreviated for readability
Runnable cmd = new Runnable() { public void run() { q.add(srcT.sRead()); } }
// tpx is the thread pool
this._tpx.scheduleAtFixedRate(cmd, 0L, 1000L, TimeUnit.MILLISECONDS);
}

现在,Java 的工作方式——如果我理解正确的话——src 等是按值传递的对象标识符,所以在上面的代码中只有一个 ISource 对象,它的标识符被添加到收集以及传递到线程池中。如果我从集合中删除标识符,该对象仍然存在,因此线程池将继续从中读取,就好像什么都没发生一样。

我的理解正确吗?如果您希望线程池注意到删除并丢弃源,那么典型的方法是什么?

最佳答案

ThreadPoolExecutor(因此 ScheduledThreadPoolExecutor)有一个 remove(Runnable) 方法。您可能还对可以取消的 FutureTask 感兴趣(尽管不会将其从工作队列中移除)。

ETA(Hanno Fietz,来自 pgras 的回答):这还需要将 Runnables 映射到源,以便 removeSource 方法可以调用 ThreadPoolExecutor.remove 并使用正确的方法。

关于java - Java 设计模式 : Does this look familiar to anyone?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/634049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com