有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我的线程忽略标志中断

嗨,伙计,我有一个简单的线程,我想在标志中断打开时终止它。 这是run方法开头的代码

conn = false;
for (int i=0; (isInterrupted() == false) && (i < TRY_CONNECT) && !conn; i++) {
    try{
        Log.d(TAG,"TRY"+i);
        sock.connect();
        conn = true;
    } catch (IOException e) {
        try {
            sleep(5000);
        } catch (InterruptedException e1) {
            Log.d(TAG,"CATCH int");
            break;
        }
    }
}
if(isInterruped() == true)
    Log.d(TAG,"INT");

在线程外,我调用了中断方法,它不会终止循环。。他看不到我所说的插话。。。怎么可能? 对于调试:在我调用中断的地方,我插入两个带有log cat的打印。。。读线程器。中断();布尔b=线程读取器。isInterrupted();日志d(标签““+b”);而在日志cat上,系统打印“假”怎么可能?我刚打电话给你


共 (2) 个答案

  1. # 1 楼答案

    当你抓住InterruptedException时,只需打破循环即可。不要依赖循环头中的isInterrupted()检查,因为当抛出InterruptedException时,中断标志被清除

  2. # 2 楼答案

    无论何时捕捉InterruptedException,这都会清除线程上的中断标志。每次抓捕时,你都需要按照以下规律做:

    try {
         sleep(5000);
    } catch (InterruptedException e1) {
         Log.d(TAG,"CATCH int");
         // _always_ re-interrupt the thread since the interrupt flag is cleared
         Thread.currentThread().interrupt();
         // you probably want to break
         break;
    }
    

    正如@Alexei所提到的,您可以在catch块中放置breakreturn以立即退出线程。但是无论哪种方式,您都应该总是重新中断Thread,以便程序的其他部分可以检测到在Thread上设置了中断条件

    有关更多信息,请参见此问题/答案:

    Why would you catch InterruptedException to call Thread.currentThread.interrupt()?