java 如何进行延迟的非阻塞函数调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10882611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a delayed non-blocking function call
提问by Thomas
I want to call the add
function of an HashSet with some delay, but without blocking the current thread. Is there an easy solution to achieve something like this:
我想add
延迟调用HashSet的函数,但不阻塞当前线程。是否有一个简单的解决方案来实现这样的目标:
Utils.sleep(1000, myHashSet.add(foo)); //added after 1 second
//code here runs immediately without delay
...
采纳答案by Tudor
You can use ScheduledThreadPoolExecutor.schedule:
您可以使用ScheduledThreadPoolExecutor.schedule:
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new Runnable() {
public void run() {
myHashSet.add(foo);
}
}, 1, TimeUnit.SECONDS);
It will execute your code after 1 second on a separate thread. Be careful about concurrent modifications of myHashSet
though. If you are modifying the collection at the same time from a different thread or trying to iterate over it you may be in trouble and will need to use locks.
它将在 1 秒后在单独的线程上执行您的代码。小心myHashSet
虽然的并发修改。如果您同时从不同的线程修改集合或尝试对其进行迭代,您可能会遇到麻烦并且需要使用锁。
回答by RalphChapin
The plain vanilla solution would be:
普通的香草解决方案是:
new Thread( new Runnable() {
public void run() {
try { Thread.sleep( 1000 ); }
catch (InterruptedException ie) {}
myHashSet.add( foo );
}
} ).start();
There's a lot less going on behind the scenes here than with ThreadPoolExecutor. TPE can be handy to keep the number of threads under control, but if you're spinning off a lot of threads that sleep or wait, limiting their number may hurt performance a lot more than it helps.
与 ThreadPoolExecutor 相比,这里的幕后工作要少得多。TPE 可以方便地控制线程数量,但如果您要分离大量休眠或等待的线程,限制它们的数量可能会损害性能,而不是帮助。
And you want to synchronize on myHashSet
if you haven't handled this already. Remember that you have to synchronize everywherefor this to do any good. There are other ways to handle this, like Collections.synchronizedMap or ConcurrentHashMap.
myHashSet
如果你还没有处理过这个,你想同步。请记住,您必须在所有地方同步才能发挥作用。还有其他方法可以处理这个问题,比如 Collections.synchronizedMap 或 ConcurrentHashMap。
回答by dbf
Check ThreadPoolExecutor.schedule()method.