开发者

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

开发者 https://www.devze.com 2022-12-31 15:42 出处:网络
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.

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.


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.

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


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

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.


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.

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).

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.

    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);
        }
    };
}


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.

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


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:

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;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号