将类实例作为线程单独运行

发布于 2025-01-08 01:37:03 字数 493 浏览 1 评论 0原文

我有这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余罪 2025-01-15 01:37:03

我不太清楚你在问什么,但我会尝试一下。

如何单独将以下代码作为线程启动?

简而言之...

Timeout.java

public class Timeout extends TimerTask {
    boolean isDone = false;

    @Override
    public void run() {
        // TODO something

        synchronized(this) {
            isDone=true;
            this.notifyAll();
        }
    }

    public synchronized void join() throws InterruptedException {
        while(!this.isDone)
            this.wait();
    }
}

TimeoutRunner.java

public class TimerRunner implements Runnable {
    @Override
    public void run() {
        Timeout timeout = new Timeout();
        Timer timer = new Timer();
        timer.schedule(timeout, 1000L);

        try {
            timeout.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            timer.cancel();
        }
    }
}

运行 TimeoutRunner 使用:

new Thread(new TimeoutRunner()).start();

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.

How can I launch the following piece of code as a thread by itself?

In short...

Timeout.java

public class Timeout extends TimerTask {
    boolean isDone = false;

    @Override
    public void run() {
        // TODO something

        synchronized(this) {
            isDone=true;
            this.notifyAll();
        }
    }

    public synchronized void join() throws InterruptedException {
        while(!this.isDone)
            this.wait();
    }
}

TimeoutRunner.java

public class TimerRunner implements Runnable {
    @Override
    public void run() {
        Timeout timeout = new Timeout();
        Timer timer = new Timer();
        timer.schedule(timeout, 1000L);

        try {
            timeout.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            timer.cancel();
        }
    }
}

Run the TimeoutRunner using:

new Thread(new TimeoutRunner()).start();

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文