简体   繁体   中英

What is the correct way to terminate thread on some condition?

some thread perform series of operation in its run method. When station closed it inform all its passengers through onStationClosed . When it happens thread must to do some action(leaveStation for example) and thread must terminate without finishing all remains operations.

What is the correct way to do it:

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

The first solution is quite good. However not very , consider wrapping operations in some small action objects and check the station status before executing each operation:

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

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

Where perform() is defined as follows:

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

A little bit far fetched, but when the number of operations grow, you'll appreciate it.

I don't quite understand the exception solution. If you throw that exception from onStationClosed() callback it will be thrown back to your event sender thread, not Passenger thread. It won't interrupt your thread.

However you can control this flow using InterruptedException . This solution is very similar to checking station status, but instead you check Thread.isInterrupted() flag. Added benefit: I/O operations and sleeps are automatically interrupted. All you have to do is calling

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM