Java 中断异常未捕获?
我正试图为一个分布式系统项目实现Raft共识算法,特别是现在我正在集中精力研究领导人选举算法。基本上有三种状态: 跟随者 候选人 领导 如果你不知道算法的话,状态通道是相当复杂的,我认为唯一有用的是知道每个状态执行不同的任务。所以我实现了这些类:Java 中断异常未捕获?,java,interrupt,future,Java,Interrupt,Future,我正试图为一个分布式系统项目实现Raft共识算法,特别是现在我正在集中精力研究领导人选举算法。基本上有三种状态: 跟随者 候选人 领导 如果你不知道算法的话,状态通道是相当复杂的,我认为唯一有用的是知道每个状态执行不同的任务。所以我实现了这些类: public class ServerStateExecutor { private ExecutorService executor; private ServerState state; private Future<
public class ServerStateExecutor {
private ExecutorService executor;
private ServerState state;
private Future<?> future;
public ServerStateExecutor()
{
executor = Executors.newSingleThreadExecutor();
SwitchFollower();
}
public void ExecuteState(ServerState state)
{
if(future!=null) {
future.cancel(true);
}
System.out.println("Submitting...");
future = executor.submit(state);
}
public void SwitchFollower() {
ExecuteState(new Follower(this));
}
public void SwitchCandidate() {
ExecuteState(new Candidate(this));//if true then no Timeout
}
public void SwitchLeader() {
ExecuteState(new Leader(this));
}
}
public abstract class ServerState implements Runnable {
protected ServerStateExecutor executor;
public abstract void run();
public ServerState(ServerStateExecutor executor)
{
this.executor = executor;
}
}
现在,正如您所想象的,当我执行Follower.run时,变量future是指任务Follower.run。那么,如果我在Follower.run期间调用SwitchCandidate,为什么future.canceltrue引发的中断异常不会被Follower.run捕获
换句话说,whyFollower.run无法捕获自身引发的中断?中断线程
如果任何线程处于睡眠或等待状态,即睡眠或等待
调用,调用线程上的中断方法,中断
引发中断异常的睡眠或等待状态。如果
线程未处于睡眠或等待状态,正在调用
中断方法执行正常行为,不中断
线程,但将中断标志设置为true
例如:
class TestInterruptingThread1 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}
而不是未来;使用future.interrupt
class TestInterruptingThread1 extends Thread{
public void run(){
try{
Thread.sleep(1000);
System.out.println("task");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
TestInterruptingThread1 t1=new TestInterruptingThread1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){System.out.println("Exception handled "+e);}
}
}