某些线程在其run
方法中执行一系列操作。当站关闭时,通过onStationClosed
通知所有乘客。发生时,线程必须执行一些操作(例如,LeaveStation),并且线程必须终止,而不必完成所有剩余操作。在某些情况下终止线程的正确方法是什么?
什么是正确的方式做到这一点:
// 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();
}
}
如何创建某种类型的堆栈来保存操作(这需要是一个具有operation()方法的接口),然后在while循环中迭代,但在循环开始时检查站状态? –
对控制流使用异常总是不好,异常只能用于异常。我认为第一个很有趣,但仍然不理想。你能解释一下你的问题吗?你为什么需要线程?为什么你不能使用回传信号向工作人员发出信号,说明当一个电台关闭时不应再做任何工作? –
我有车站和乘客。乘客去车站并尝试进入车站。乘客在车站做他们需要的东西,一旦车站关闭,即使他们没有完成他们计划做的所有事情,他们也需要离开。 – theateist