9

我想调用addHashSet 的函数有一些延迟,但不阻塞当前线程。是否有一个简单的解决方案来实现这样的事情:

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

3 回答 3

13

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.

And you want to synchronize on myHashSet if you haven't handled this already. Remember that you have to synchronize everywhere for this to do any good. There are other ways to handle this, like Collections.synchronizedMap or ConcurrentHashMap.

于 2012-06-04T16:19:11.400 回答
12

您可以使用ScheduledThreadPoolExecutor.schedule

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);

exec.schedule(new Runnable() {
          public void run() {
              myHashSet.add(foo);
          }
     }, 1, TimeUnit.SECONDS);

它将在 1 秒后在单独的线程上执行您的代码。小心同时修改myHashSet虽然。如果您同时从不同的线程修改集合或尝试对其进行迭代,您可能会遇到麻烦并且需要使用锁。

于 2012-06-04T14:04:32.377 回答
0

检查ThreadPoolExecutor.schedule()方法。

于 2012-06-04T14:02:00.583 回答