Java线程中断()。这是正常的例外吗?

时间:2012-12-05 20:39:49

标签: java multithreading

我这样开始我的线程:

public void startTask(Runnable r)
{
    running = true;
    Log.i(tag, "-----------start.Runnable-----------");

    final Thread first = new Thread(r);
    currentTask = first;
    first.start();

    Thread second = new Thread(new Runnable() {

        @Override
        public void run() {
            try{
                first.join();
            }
            catch(InterruptedException e){

            }
            running = false;
        }
    });

    second.start();

}

当我想取消当前的操作时,我正在根据这篇文章使用Theread这样做:http://forward.com.au/javaProgramming/HowToStopAThread.html

public void cancelTask()
{
    Log.i(tag, "-----------cancelTask()-----------");
    try{
        currentTask.interrupt();
        running = false;
    }
    catch(SecurityException e){
        e.printStackTrace();
    }
}

应用程序仍然在cancelTask​​之后运行,但我有异常:

12-05 20:29:00.274: W/System.err(13533): java.lang.InterruptedException
12-05 20:29:00.274: W/System.err(13533):    at java.lang.VMThread.sleep(Native Method)
12-05 20:29:00.294: W/System.err(13533):    at java.lang.Thread.sleep(Thread.java:1047)
12-05 20:29:00.294: W/System.err(13533):    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:331)
12-05 20:29:00.304: W/System.err(13533):    at com.rsd.myfirstapp3.ProgressServiceActivity$2.run(ProgressServiceActivity.java:174)
12-05 20:29:00.314: W/System.err(13533):    at java.lang.Thread.run(Thread.java:864)

使用线程进行此类操作是正常的异常吗?

1 个答案:

答案 0 :(得分:0)

线程自行停止或由外部进程停止。表示线程在执行任何操作后完成其执行,此时不会抛出InterruptedException(这是显而易见的)。但是父线程(启动线程的线程)可能希望在执行之间停止执行线程,在这种情况下会抛出异常InterruptedException并且线程会收到此异常。这主要是因为当外部进程/父线程停止时,这个步骤想要做某事(清理资源,关闭IO等)。 Refer