处理InterruptedException的最佳实践

IBM开发者论坛2006年写的一篇关于InterruptedException的最佳实践,还是很不错的。


方式1:把中断异常InterruptedException抛给调用者来处理,比如说:

public Task getTask() throws InterruptedException { 
        return queue.take();
}


方式2:在中断异常抛出前,可以做一些保存数据的操作:

public class PlayerMatcher {
    private PlayerSource players;
 
    public PlayerMatcher(PlayerSource players) { 
        this.players = players; 
    }
 
    public void matchPlayers() <strong>throws InterruptedException</strong> { 
        Player playerOne, playerTwo;
         try {
             while (true) {
                 playerOne = playerTwo = null;
                 // Wait for two players to arrive and start a new game
                 playerOne = players.waitForPlayer(); // 有可能会抛出中断异常
                 playerTwo = players.waitForPlayer(); // 有可能会抛出中断异常
                 startNewGame(playerOne, playerTwo);
             }
         }
         catch (InterruptedException e) {  
             
             if (playerOne != null)                  // 把已经连接上的玩家1保存下来
                 players.addFirst(playerOne);   
             
             throw e;  // 抛出异常

         }
    }
}
代码中是两个游戏玩家的线程必须同时到达,才能开始游戏,如果在玩家1已经连接上,玩家2发生了中断异常了,此时在抛出中断异常前,可以将已经连接上的玩家保存下来。


方式3:不要忽略中断异常,每次发生中断异常后,会清除当前线程的中断状态。可以在中断异常的catch块中重新设置中断状态。

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;
 
    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }
 
    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
             // 恢复中断状态
             Thread.currentThread().interrupt();
         }
    }
}

可以看一下Thread的interrupt()方法,只是重新设置为中断状态:


    public static boolean interrupted() {
	return currentThread().isInterrupted(true);
    }


方式4:设计为可以取消任务的方式,当取消任务时抛出中断异常,任务捕获到异常后,终止执行任务。

public class PrimeProducer extends Thread {
    private final BlockingQueue<BigInteger> queue;
 
    PrimeProducer(BlockingQueue<BigInteger> queue) {
        this.queue = queue;
    }
 
    public void run() {
        try {
            BigInteger p = BigInteger.ONE;
            while (!Thread.currentThread().isInterrupted())
                queue.put(p = p.nextProbablePrime());
        } catch (InterruptedException consumed) {
            /* Allow thread to exit */
        }
    }
 
    public void cancel() { interrupt(); }
}


方式5:设计为一个不可中断的任务,也就是即使发生中断了,还得让任务继续执行下去。

public Task getNextTask(BlockingQueue<Task> queue) {
    boolean interrupted = false;
    try {
        while (true) {
            try {
                return queue.take();
            } catch (InterruptedException e) {
                interrupted = true;
                // fall through and retry
            }
        }
    } finally {
        if (interrupted)
            Thread.currentThread().interrupt();
    }
}


原文参考:https://www.ibm.com/developerworks/java/library/j-jtp05236/index.html

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当线程在阻塞状态时,可能会抛出InterruptedException异常。当线程被中断时,就会抛出这个异常,以表示线程的中断状态。在处理InterruptedException异常时,有一些常见的方法。 首先,可以选择捕获并处理InterruptedException异常。这意味着在捕获异常之后,你可以选择执行一些特定的操作,例如记录日志、通知其他线程或者进行清理工作。在捕获InterruptedException异常时,可以使用try-catch语句将代码包裹起来,并在catch块中处理异常情况。 当捕获InterruptedException异常时,一种处理方法是重新设置中断状态。通过调用Thread.currentThread().interrupt()方法,可以将当前线程的中断状态重新设置为true。这样可以确保更高层的代码能够检测到中断状态,并对中断作出响应。 另一种处理方法是将InterruptedException异常向上抛出。如果你的代码没有合适的方式来处理这个异常,你可以选择将它抛给调用方,让调用方来处理。在这种情况下,你可以在方法声明中添加throws InterruptedException来声明该方法可能抛出这个异常。 总之,处理InterruptedException异常需要根据具体情况来决定。你可以选择捕获并处理异常,重新设置中断状态,或将异常向上抛出让调用方来处理。这样可以确保对中断状态进行适当的处理。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [不学无数——InterruptedException异常处理](https://blog.csdn.net/weixin_33998125/article/details/89627134)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值