[英]What is the correct way to terminate thread on some condition?
some thread perform series of operation in its run
method. 一些线程在其run
方法中执行一系列操作。 When station closed it inform all its passengers through onStationClosed
. 车站关闭时,它将通过onStationClosed
通知所有乘客。 When it happens thread must to do some action(leaveStation for example) and thread must terminate without finishing all remains operations. 发生这种情况时,线程必须执行某些操作(例如,leaveStation),并且线程必须终止而未完成所有剩余操作。
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 station
status before executing each operation: 但是不是很干燥 ,请考虑在一些小的操作对象中包装操作,并在执行每个操作之前检查station
状态:
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: 其中perform()
定义如下:
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. 如果从onStationClosed()
回调引发该异常,则它将被引发回事件发送者线程,而不是Passenger
线程。 It won't interrupt your thread. 它不会中断您的线程。
However you can control this flow using InterruptedException
. 但是,您可以使用InterruptedException
来控制此流程。 This solution is very similar to checking station status, but instead you check Thread.isInterrupted()
flag. 此解决方案与检查站状态非常相似,但是您可以检查Thread.isInterrupted()
标志。 Added benefit: I/O operations and sleeps are automatically interrupted. 额外的好处:I / O操作和睡眠会自动中断。 All you have to do is calling 您要做的就是打电话
Thread passenger = new Passenger();
passenger.interrupt();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.