java – 在某些条件下终止线程的正确方法是什么?

某些线程在其run方法中执行一系列操作.当车站关闭时,它通过onStationClosed通知所有乘客.当它发生时,线程必须做一些动作(例如,离开站点)并且线程必须终止而不完成所有剩余操作.

这样做的正确方法是什么:

// 1 - By checking station's state between each operationN?

public class Passenger extends Thread
{
     Station station;
     public void onStationClosed()
     {
          // Do some action before thread terminates
     }
     @Override
     public void run()
     {
         operation1();
         if(station.getState == Station.Closed) return;
         operation2();
         if(station.getState == Station.Closed) return;
         operation3();
         if(station.getState == Station.Closed) return;
         ..
         operationN();
     }
}

// 2 - Throw StationClosedException from onStationClosed and catch it in Station.

public class Passenger extends Thread
{
    Station station;
    public void onStationClosed()
    {
         // Do some action before thread terminates
         throw new StationClosedException();
    }
    @Override
    public void run()
    {
        operation1();
        operation2();
        ..
        operationN();
    }
}

最佳答案 第一个解决方案非常好.但是不是很多
dry,考虑在一些小动作对象中包装操作并在执行每个操作之前检查站状态:

List<Operation> operations = Arrays.asList(new Operation1(), new Operation2(), new Operation3());

for(Operation operation: operations) {
  if(!perform(operation)) {
    return;
  }
}

其中perform()定义如下:

private boolean perform(Operation operation) {
  if(station.getState == Station.Closed)
    return false;
  operation.run();
  return true;
}

有点牵强,但当操作次数增加时,你会欣赏它.

我不太了解异常解决方案.如果从onStationClosed()回调中抛出该异常,它将被抛回到事件发送方线程,而不是Passenger线程.它不会打断你的线程.

但是,您可以使用InterruptedException控制此流.此解决方案与检查工作站状态非常相似,而是检查Thread.isInterrupted()标志.增加的好处:I / O操作和睡眠会自动中断.你所要做的就是打电话

Thread passenger = new Passenger();
passenger.interrupt();
点赞