Stopping looping thread in Java

后端 未结 6 1652
我寻月下人不归
我寻月下人不归 2020-12-29 16:13

I\'m using a thread that is continuously reading from a queue.

Something like:

public void run() {
    Object obj;
    while(true) {
        synchron         


        
6条回答
  •  暖寄归人
    2020-12-29 16:23

    Why not use a scheduler which you simply can stop when required? The standard scheduler supports repeated scheduling which also waits for the worker thread to finish before rescheduling a new run.

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleWithFixedDelay(myThread, 1, 10, TimeUnit.SECONDS);
    

    this sample would run your thread with a delay of 10 sec, that means when one run finishes, it restarts it 10 seconds later. And instead of having to reinvent the wheel you get

    service.shutdown()
    

    the while(true) is not necessary anymore.

    ScheduledExecutorService Javadoc

提交回复
热议问题