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