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 dry, consider wrapping operations in some small action objects and check the
stationstatus before executing each operation:Where
perform()is defined as follows: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, notPassengerthread. 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 checkThread.isInterrupted()flag. Added benefit: I/O operations and sleeps are automatically interrupted. All you have to do is calling