java stop和int,JAVA并发任务中止的isinterrupted,interupted()
將一個任務的不同步驟劃分成子任務放到不同的線程里,這樣實現(xiàn)的并行化并不是一個很好的辦法。這些異質的子任務之間有協(xié)作關系,需要有效的機制
同步——而額外的同步會對性能有一定影響,更重要的是會影響scalability。一個更好的辦法是將任務劃分成多個獨立的同質子任務,這樣子任務可以在不需要
同步的情況下并行執(zhí)行,性能提升的效果更明顯,scalability也更強。
2.4. 任務的取消與終止
Java中沒有安全的終止一個線程的方法,因此必須采用協(xié)作的方式來實現(xiàn)。
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狀態(tài);interrupted方法清除并返回interrupted狀態(tài)。
如果打斷發(fā)生時線程阻塞在sleep,wait之類的方法中,那它們會重置interrupted狀態(tài)并拋出InterruptedException。這意味著在抓InterruptedException的時候調用isInterrupted會返回false。
如果打斷發(fā)生在線程正常運行時,那打斷只會將interrupted標志改成true,線程需要自己檢查并清除這個標志。
如果在進入阻塞方法之前線程就已經(jīng)被打斷并且interrupted標志未被重置,那這些阻塞方法會立刻拋出InterruptedException。見如下例子:
這個程序的輸出:
Because each thread has its own interruption policy, you should not interrupt a thread unless you know what interruption means to that thread.
總結
以上是生活随笔為你收集整理的java stop和int,JAVA并发任务中止的isinterrupted,interupted()的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 广汽埃安昊铂 HT 车型 11 月 15
- 下一篇: 华硕:若 ROG 笔记本电脑散热效能检测