如何进行延迟的非阻塞函数调用 [英] How to make a delayed non-blocking function call

查看:67
本文介绍了如何进行延迟的非阻塞函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想稍微延迟地调用HashSet的add函数,但又不要阻塞当前线程.是否有一个简单的解决方案来实现以下目标:

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:

Utils.sleep(1000, myHashSet.add(foo)); //added after 1 second
//code here runs immediately without delay
...

推荐答案

您可以使用它将在一个单独的线程上执行1秒后执行您的代码.但是,请注意同时对myHashSet进行修改.如果您要同时从其他线程修改集合或尝试对其进行迭代,则可能会遇到麻烦,需要使用锁.

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.

这篇关于如何进行延迟的非阻塞函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆