将类实例作为线程单独运行
我有这段代码:
Timeout s = new Timeout();
Timer timer = new Timer();
timer.schedule(s, 1000L); // fires after 1 second
如何单独将以下代码作为线程启动?我是否需要将计时器和超时传递给可运行对象,然后启动它?如果线程的 Run() 在计时器触发之前结束,会发生什么情况?
我正在考虑这样做:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
Timeout s = new Timeout(); // Timeout is a runnable
ses.schedule(s, 10, TimeUnit.SECONDS);
但是如何在超时后退出线程?一段时间后我的线程就用完了,
谢谢
I have this piece of code:
Timeout s = new Timeout();
Timer timer = new Timer();
timer.schedule(s, 1000L); // fires after 1 second
How can I launch the following piece of code as a thread by itself? Would I need to pass the timer and Timeout to a Runnable and then start it? What happens if the thread's Run() ends before the timer is fired?
I am thinking of doing this instead:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
Timeout s = new Timeout(); // Timeout is a runnable
ses.schedule(s, 10, TimeUnit.SECONDS);
but how do I exit the thread after the timeout? I run out of thread after a while
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不太清楚你在问什么,但我会尝试一下。
简而言之...
Timeout.java
TimeoutRunner.java
运行 TimeoutRunner 使用:
join 方法将阻塞线程,直到超时任务完成执行。这时候你就可以关闭定时器了。然而,这会创建大量线程,并且在我看来是糟糕的编程。
当您创建 Timer 实例时,会创建一个线程来执行 Timeout#run() 方法。计时器有自己的 run 方法,该方法会阻塞,直到您的任务准备好执行为止。给定的超时时间过去后,计时器将解除阻塞并执行您的超时。
您的 TimeoutRunner 线程将阻塞,直到超时操作完成。只有这样这个线程才能消亡。
Timer 类非常有限。您需要为每个任务创建一个新实例。在我的选择中,ScheduledExecutorService 是一个更好的选择。只要您计划执行任务,就保持 ScheduledExecutorService 处于打开状态。如果您需要诸如计划缓存线程池之类的东西,请随意使用我的开源项目之一中的此类(调度程序)。这对于缓存线程池非常有效。
I'm not exactly sure what you're asking, but I'll give it a shot.
In short...
Timeout.java
TimeoutRunner.java
Run the TimeoutRunner using:
The join method will block the thread until the timeout task has completed execution. At that time you can close the Timer. This is, however, a lot of thread creation, and IMO bad programming.
When you create a Timer instance, a thread is created to execute the Timeout#run() method. The timer has it's own run method that blocks until your task is ready for execution. After the given timeout period elapses, the timer unblocks and executes your timeout.
Your TimeoutRunner thread will block until the timeout operation completes. Only then can this thread die.
The Timer class is very limited. You need to create a new instance for every task. In my option, the ScheduledExecutorService is a better option. Keep the ScheduledExecutorService open for as long as you plan on executing tasks. If you need something like a scheduled cached thread pool, feel free to use this class from one of my open-source projects (Scheduler). This works great with a cached thread pool.