如何设置无限循环并打破它。(Java线程)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2854812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:41:42  来源:igfitidea点击:

how to set a infinite loop and break it. (Java threads)

javamultithreading

提问by Nubkadiya

i have set a thread and i want to run it using a loop. so this thread should run in the loop and break in a certain time and again run the loop.

我已经设置了一个线程,我想使用循环来运行它。所以这个线程应该在循环中运行并在某个时间中断并再次运行循环。

please i have no clue how to do this. can someone guide me.

请我不知道如何做到这一点。有人可以指导我。

采纳答案by mdma

Assuming you're running on JDK 1.5 or newer (where memory model was clarified and improved) you can use

假设您在 JDK 1.5 或更高版本上运行(其中内存模型得到了澄清和改进),您可以使用

public class MyRunnable extends Runnable
{
   private volatile boolean cancelled;

   public void run() {
      while (!cancelled) { 
         doStuff();
      }
   }

   public void cancel()
   {
      cancelled = true;  
   }

   public boolean isCancelled() {
      return cancelled;
   }
}j

Alternatively, use java.util.concurrent.Future, and FutureTask, which supports cancellation out of the box.

或者,使用java.util.concurrent.Future和 FutureTask,它支持开箱即用的取消。

回答by vodkhang

I can only give you some suggestion only. You can set a flag like isThreadRunning, and then when that flag is true, you run the loop, if it is not true, you out of the loop. About running the loop again, I think you can create a new thread for that. Here is some code snippet:

我只能给你一些建议。你可以设置一个像 isThreadRunning 这样的标志,然后当这个标志为真时,你运行循环,如果它不为真,你就退出循环。关于再次运行循环,我认为您可以为此创建一个新线程。这是一些代码片段:

public class A extends Thread {
  public boolean isThreadRunning = true;
  public void run() {
    while(isThreadRunning) {
    // do task
    }    
  }
}

When a certain time happens, or another thread wants to stop that thread, you can just call A.isThreadRunning = false;

当某个时间发生,或者另一个线程想要停止该线程时,您可以调用 A.isThreadRunning = false;

回答by Ravindra Gullapalli

Write your run method of your thread like this

像这样编写线程的运行方法

public void run(){
   while (true){
       if (condition){
          // your logic
       }
       java.lang.Thread.sleep(1000L);
   }
}

In the above code, the loop is an infinite loop which will execute every second (1000 milli seconds) and your logic will be executed only if the condition satisfied.

在上面的代码中,循环是一个无限循环,每秒(1000 毫秒)执行一次,并且只有在满足条件时才会执行您的逻辑。

If you want to increase the pause time to 2 seconds, change 1000Lto 2000L

如果要将暂停时间增加到 2 秒,请更改1000L2000L

回答by Affe

Java has a built in mechanism for having a thread do something and then wait for a while to do it again, called Timer. You can put what would be inside your loop inside the Run()method of a TimerTask, and then tell the timer how often you want it done.

Java 有一个内置的机制,可以让线程做某事,然后等待一段时间再做,称为Timer. 您可以将循环中的内容放入 a 的Run()方法中TimerTask,然后告诉计时器您希望它多久完成一次。

TimerTask task = new TimerTask() {
  @Override
  public void run() {
    //do some processing
  }
};

Timer timer = new Timer();
timer.schedule(task, 0l, 1000l); //call the run() method at 1 second intervals

It is of course your job to shut it down when the program is done.

当程序完成时关闭它当然是你的工作。

http://java.sun.com/javase/6/docs/api/java/util/Timer.html

http://java.sun.com/javase/6/docs/api/java/util/Timer.html

回答by John Vint

I feel we are missing the Executors!

我觉得我们缺少执行者!

There is an ScheduledExecutorService that you can use to run a task, then run again after a fixed amount of time. Its similar to the TimerTask but easier to manage and better maintained.

您可以使用 ScheduledExecutorService 来运行任务,然后在固定时间后再次运行。它类似于 TimerTask,但更易于管理和更好地维护。

private final ScheduledExecutorService scheduler = 
                           Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                //do work here  
            }
    }, 1, TimeUnit.SECONDS);

The Executor will scheudle this task every second and also can return a ScheduledFuture that you can use to either cancel or get result (if you are using a Callable instead of runnable).

Executor 将每秒调度此任务,并且还可以返回一个 ScheduledFuture,您可以使用它来取消或获取结果(如果您使用的是 Callable 而不是 runnable)。

Edit: CPerkins brings up a good point. How do we cancel after a certain amount of time then re execute. This is a bit much but it gets the job done I think.

编辑:CPerkins 提出了一个很好的观点。我们如何在一定时间后取消然后重新执行。这有点多,但它完成了我认为的工作。

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ExecutorService executor = Executors.newFixedThreadPool(1);

public void execute(){
    executor.submit(scheduleTask());
}
public Runnable scheduleTask(){
    return new Runnable() {
        public void run() {
            final ScheduledFuture cancel = scheduler.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    // do work here
                }
            }, 0, 1, TimeUnit.SECONDS);
            scheduler.schedule(new Runnable() {
                public void run() {
                    cancel.cancel(true);
                    execute();
                }
            }, 1, TimeUnit.MINUTES);
        }
    };
}