分享

JAVA并发任务中止的isinterrupted,interupted()

 hh3755 2013-03-28

将一个任务的不同步骤划分成子任务放到不同的线程里,这样实现的并行化并不是一个很好的办法。这些异质的子任务之间有协作关系,需要有效的机制 同步——而额外的同步会对性能有一定影响,更重要的是会影响scalability。一个更好的办法是将任务划分成多个独立的同质子任务,这样子任务可以在不需要 同步的情况下并行执行,性能提升的效果更明显,scalability也更强。

2.4. 任务的取消与终止

  • Java中没有安全的终止一个线程的方法,因此必须采用协作的方式来实现。
There is no safe way to preemptively stop a thread in Java, and therefore no safe way to preemptively stop a task. There are only cooperative mechanisms, by which the task and the code requesting cancellation follow an agreed-upon protocol.
  • 再抓InterruptedException的时候要三思,要想好该做些什么,因为:
Thread interruption is a cooperative mechanism for a thread to signal another thread that it should, at its convenience and if it feels like it, stop what it is doing and do something else.
  • isInterrupted方法返回线程当前的interrupted状态;interrupted方法清除并返回interrupted状态。
  • 如果打断发生时线程阻塞在sleep,wait之类的方法中,那它们会重置interrupted状态并抛出InterruptedException。这意味着在抓InterruptedException的时候调用isInterrupted会返回false。
  • 如果打断发生在线程正常运行时,那打断只会将interrupted标志改成true,线程需要自己检查并清除这个标志。
  • 如果在进入阻塞方法之前线程就已经被打断并且interrupted标志未被重置,那这些阻塞方法会立刻抛出InterruptedException。见如下例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class InterruptBeforeSleep {
    public static void main(String[] args) {
        Runnable task = new Runnable() {
             
            public void run() {
                System.out.println("Running task");
                double dummy = 0.11111;
                for (double i = 2.0; i < 100000000.0; i++) {
                    dummy *= (i / (i-1));
                }
                System.out.println("Result is: " + dummy);
                System.out.println("About to sleep");
                try {
                    Thread.sleep(SECONDS.toMillis(20));
                } catch (InterruptedException e) {
                    System.out.println("I'm interrupted");
                    // The interrupt status is cleared when Thread.sleep throws InterruptedException
                    System.out.println("I'm interrupted? " + Thread.currentThread().isInterrupted());
                }
            }
        };
         
        Thread t = new Thread(task);
        t.start();
        t.interrupt();
        System.out.println("Main interrupted the task thread");
    }
}
这个程序的输出:
1
2
3
4
5
6
Main interrupted the task thread
Running task
Result is: 1.1110999894874712E7
About to sleep
I'm interrupted
I'm interrupted? false
  • Because each thread has its own interruption policy, you should not interrupt a thread unless you know what interruption means to that thread.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多