如何在Java中运行一个线程一小时。

huangapple go评论75阅读模式
英文:

How to run a thread for one hour in java

问题

以下是翻译好的内容:

我将会接收一个属性,并且我想要为那个属性运行一个持续1小时的任务 - 监控和记录与该属性相关的事项。在那一个小时之后,任务将会停止。

有没有一种方法可以运行一个任务、线程或者作业,持续一个小时,给定一个该线程的标识?据我所知,SchedulerExecutorService会在延迟和一定间隔之后运行。但是如何在一个小时之后停止那个特定线程的任务呢?

这里还要注意一点 - 有一个线程会运行一个小时然后终止。在这一个小时的线程内部,还有另一个线程会每5分钟做一些工作。总的来说,我希望一个任务运行一个小时,然后在这个任务内部,还有另一个每5分钟运行一次的线程。

请帮忙。

class Task1 implements Runnable {
    String abc;
    private final ScheduledExecutorService monitorService;
    private boolean isShutDown = false;

    public Task1(String abc) {
        this.abc = abc;
        this.monitorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("checker-%s").build());
    }

    @Override
    public void run()
    {
        Stopwatch stopwatch = Stopwatch.createStarted();
        monitorService.scheduleAtFixedRate(new Task2(abc), 2, 300000, TimeUnit.MILLISECONDS);
        long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        if(elapsed == 3600000) {
            shutdownAndAwaitTermination(monitorService);
            isShutDown = monitorService.isShutdown() || monitorService.isTerminated();
        }
    }

    public boolean isShutDown()
    {
        return isShutDown;
    }
}

public class Task2 implements Runnable //This should run every 5 minutes
{
    private String abc;

    public Task2(String abc) {
        this.abc = abc;
    }

    @Override
    public void run()
    {
        System.out.println(abc);
    }
}

Task1 task1 = new Task1("abc");
task1.run(); //This should run for 1 hour and terminate

(注意:由于您要求只返回翻译好的部分,我已经省略了代码中的一些细节,如shutdownAndAwaitTermination方法的实现以及引用的外部库的导入等。如果您需要完整的代码以及细节,请随时提问。)

英文:

I will be receiving an attribute and I want to run a job for that attribute for 1 hour - monitoring and logging things related to that attribute. After that one hour, the job will stop.

Is there a way to run a task, thread or a job for one hour given a id for that thread? As far as I know, the SchedulerExecutorService runs with a delay and after a certain interval. But how can I stop the job for that particular thread after one hour.

One more thing to note here is - there is a thread which will run for one hour and terminate. And there is another thread inside the one hour thread which will be doing some work every 5 minutes. So all in all I want a job to run for one hour and then inside that thread, another thread which will run every 5 minutes.

Kindly help.

class Task1 implements Runnable {
String abc;
private final ScheduledExecutorService monitorService;
private boolean isShutDown = false;
public Task1(String abc) {
this.abc = abc;
this.monitorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("checker-%s").build());
}
@Override
public void run()
{
Stopwatch stopwatch = Stopwatch.createStarted();
monitorService.scheduleAtFixedRate(new Task2(abc), 2, 300000, TimeUnit.MILLISECONDS);
long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
if(elapsed == 3600000) {
shutdownAndAwaitTermination(monitorService);
isShutDown = monitorService.isShutdown() || monitorService.isTerminated();
}
}
public boolean isShutDown()
{
return isShutDown;
}
}
public class Task2 implements Runnable //This should run every 5 minutes
{
private String abc;
public Task2(abc) {
this.abc = abc;
}
@Override
public void run()
{
System.out.println(abc);
}
}
Task1 task1 = new Task1("abc");
task1.run(); //This should run for 1 hour and terminate

答案1

得分: 2

唯一正确的终止线程的方法是让线程本身退出 run() 方法。不要使用 stop、interrupt 或者 kill 线程 - 详细解释请参阅文档

可以像这样实现:

public void run() {
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime < 3600000) {
        // ... 在这里执行操作 ...
    }
}
英文:

The only proper way to terminate a thread is for a thread itself to exit the run() method. Do not stop, interrupt or kill the thread - read the documentation for explanation why.

Do something like this:

public void run() {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime &lt; 3600000) {
// ... do your stuff here ...
}
}

huangapple
  • 本文由 发表于 2020年9月16日 09:45:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63911994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定