日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java多线程基本概述(二十)——中断

發布時間:2025/5/22 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java多线程基本概述(二十)——中断 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

線程中斷我們已經直到可以使用?interrupt()?方法,但是你必須要持有?Thread?對象,但是新的并發庫中似乎在避免直接對?Thread?對象的直接操作,盡量使用?Executor?來執行所有的請求。如果你在?ExecutorService?上調用?shutdownNow()?.那么它將發送一個?interrupt()?調用給它啟動的所有線程。如果只是調用?shutdown()?,則不會發送中斷。如果只是向中斷某一個任務呢。如果使用ExcecutorService那么我們通過?submit()?來啟動任務而不是通過?execut()?來啟動任務,這樣我們可持有該任務的上下文。?submit()?將返回一個泛型的?Future<?>?對象。持有這個關鍵字的對象的主要目的即可以接收?call()?方法的返回值,通過?get()?方法,也可以調用其?cancel()?方法,來中斷某個特定的任務。。

A Future represents the result of an asynchronous computation. Future 表示異步計算的結果
Methods are provided to check if the computation is complete,to wait for its completion, and to retrieve the result of the computation.
它提供了檢查計算是否完成的方法,以等待計算的完成,并獲取計算的結果
The result can only be retrieved using method get when the computation has completed,
blocking if necessary until it is ready. Cancellation is performed by the cancel method.
計算完成后只能使用get方法來獲取結果,如有必要,計算完成前可以阻塞此方法。取消則由cancel方法來執行
Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled.
還提供了其他方法,以確定任務是正常完成還是被取消了。一旦計算完成,就不能再取消計算
If you would like to use a Future for the sake of cancellability but not provide a usable result,
you can declare types of the form Future<?> and return null as a result of the underlying task. Sample Usage (Note that the following classes are all made-up.)
如果為了可取消性而使用?Future?但又不提供可用的結果,則可以聲明?Future<?>?形式類型、并返回?null?作為底層任務的結果。

cancle()api

boolean cancel(boolean mayInterruptIfRunning) Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task. After this method returns, subsequent calls to isDone will always return true. Subsequent calls to isCancelled will always return true if this method returned true. Parameters: mayInterruptIfRunning - true if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete Returns: false if the task could not be cancelled, typically because it has already completed normally; true otherwise 試圖取消對此任務的執行。如果任務已完成、或已取消,或者由于某些其他原因而無法取消,則此嘗試將失敗。當調用 cancel 時,如果調用成功,而此任務尚未啟動,則此任務將永不運行。如果任務已經啟動,則 mayInterruptIfRunning 參數確定是否應該以試圖停止任務的方式來中斷執行此任務的線程。 此方法返回后,對 isDone() 的后續調用將始終返回 true。如果此方法返回 true,則對 isCancelled() 的后續調用將始終返回 true。 參數: mayInterruptIfRunning - 如果應該中斷執行此任務的線程,則為 true;否則允許正在運行的任務運行完成 返回: 如果無法取消任務,則返回 false,這通常是由于它已經正常完成;否則返回 true

阻塞的種類:

1、等待阻塞:運行的線程執行wait()方法,JVM會把該線程放入等待池中。
2、同步阻塞:運行的線程在獲取對象的同步鎖時,若該同步鎖被別的線程占用,則JVM會把該線程放入鎖池中。
3、其他阻塞:運行的線程執行sleep()或join()方法,或者發出了I/O請求時,JVM會把該線程置為阻塞狀態。當sleep()狀態超時、join()等待線程終止或者超時、或者I/O處理完畢時,線程重新轉入就緒狀態。

這個例子展示了幾種不同的阻塞

import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit;/*** Created by huaox on 2017/4/20.**/class SleepBlock implements Runnable{@Overridepublic void run() {try {TimeUnit.SECONDS.sleep(100);} catch (InterruptedException e) {System.out.println("InterruptedException by sleep()");}System.out.println("Exiting SleepBlocked.run()");} }class IOBlock implements Runnable{private InputStream inputStream;public IOBlock(InputStream inputStream) {this.inputStream = inputStream;}@Overridepublic void run() {try {System.out.println("Waiting for read(): ");inputStream.read();} catch (IOException e) {if(Thread.currentThread().isInterrupted()){System.out.println("");}else{System.out.println("DON'T Interrupted from block IO");throw new RuntimeException(e);}}System.out.println("Exiting IOBlocked.run()");} } //同步阻塞 class SynchronizedBlock implements Runnable{synchronized void f(){ //永遠不釋放鎖while (true)Thread.yield();}public SynchronizedBlock() {new Thread(){@Overridepublic void run() {f();}}.start();}@Overridepublic void run() {System.out.println("outer thread trying to call f()");f();System.out.println("Exiting SynchronizedBlock.run()");} }public class Interrupting {private static ExecutorService executorService = Executors.newCachedThreadPool();static void test(Runnable runnable) throws InterruptedException{Future<?> future = executorService.submit(runnable);TimeUnit.MILLISECONDS.sleep(100);System.out.println("interrupting "+runnable.getClass().getName());future.cancel(true);System.out.println("interrupt sent to "+runnable.getClass().getName());}public static void main(String[] args) throws InterruptedException {test(new SleepBlock());test(new IOBlock(System.in));test(new SynchronizedBlock());TimeUnit.SECONDS.sleep(3);/* System.out.println("Aborting with System.exit(0)");System.exit(0);*/} }

下面分別測試SleepBlock,IOBlock,SynchronizedBlock。運行結果

SleepBlock:可中斷阻塞

interrupting SleepBlock InterruptedException by sleep() Exiting SleepBlocked.run() interrupt sent to SleepBlock Aborting with System.exit(0)Process finished with exit code 0

IOBlock:不可中斷阻塞

Waiting for read(): interrupting IOBlock interrupt sent to IOBlock Aborting with System.exit(0)Process finished with exit code 0

SynchronizedBlock:不可中斷阻塞

outer thread trying to call f() interrupting SynchronizedBlock interrupt sent to SynchronizedBlock Aborting with System.exit(0)Process finished with exit code 0

從輸出中可以看到,你能夠中斷對sleep()的調用,(或者任何要求拋出InterrptedException的調用)。但是,你不能中斷正在視圖獲取synvhronized鎖或者視圖執行I/O操作的線程。但是對于IO。可以使用一個比較笨拙的方法。即關閉任務在其發生阻塞的底層資源。

import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;/*** Created by huaox on 2017/4/20.**/ public class CloseResource {public static void main(String[] args) throws Exception {ExecutorService executorService = Executors.newCachedThreadPool();ServerSocket serverSocket = new ServerSocket(8888);InputStream socketInput = new Socket("localhost",8888).getInputStream();executorService.execute(new IOBlock(socketInput));//executorService.execute(new IOBlock(System.in)); TimeUnit.MILLISECONDS.sleep(100);System.out.println("shutting down all thread");executorService.shutdownNow();TimeUnit.SECONDS.sleep(1);System.out.println("Closing "+ serverSocket.getClass().getName());serverSocket.close();/* TimeUnit.SECONDS.sleep(1);System.out.println("Closing "+ System.in.getClass().getName());System.in.close();*/} }

輸出結果:對于serverSocket.可以關閉底層資源關閉

Waiting for read(): shutting down all thread Closing java.net.ServerSocket InterruptedException by block IO Exiting IOBlocked.run() Closing java.io.BufferedInputStreamProcess finished with exit code 0

程序正常終止,小紅點變灰。如果對于文件IO。

import java.io.File; import java.io.FileInputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;/*** Created by huaox on 2017/4/20.**/ public class CloseResource {public static void main(String[] args) throws Exception {ExecutorService executorService = Executors.newCachedThreadPool();FileInputStream fileInputStream = new FileInputStream(new File("D:\\soft\\CCleaner.exe"));/*ServerSocket serverSocket = new ServerSocket(8888);InputStream socketInput = new Socket("localhost",8888).getInputStream();*///executorService.execute(new IOBlock(socketInput));//executorService.execute(new IOBlock(System.in));executorService.execute(new IOBlock(fileInputStream));TimeUnit.MILLISECONDS.sleep(100);System.out.println("shutting down all thread");executorService.shutdownNow();/* TimeUnit.SECONDS.sleep(1);System.out.println("Closing "+ serverSocket.getClass().getName());serverSocket.close();*/TimeUnit.SECONDS.sleep(1);System.out.println("Closing "+ fileInputStream.getClass().getName());System.in.close();} }

輸出結果:

Waiting for read(): Exiting IOBlocked.run() shutting down all thread Closing java.io.FileInputStreamProcess finished with exit code 0

也是可以關閉的。但我們應該用NIO更好的進行控制。

/*** Created by huaox on 2017/4/20.**/ class NIOBlock implements Runnable{private final SocketChannel socketChannel;public NIOBlock( SocketChannel socketChannel) {this.socketChannel = socketChannel;}@Overridepublic void run() {try {System.out.println("Waiting for read(): "+this);socketChannel.read(ByteBuffer.allocate(1));}catch (ClosedByInterruptException e) {System.out.println("ClosedByInterruptException");}catch (AsynchronousCloseException e){System.out.println("AsynchronousCloseException");}catch (IOException e){System.out.println("IOException");}System.out.println("Exiting NIOBlocked.run() "+this);} } public class CloseResource {public static void main(String[] args) throws Exception {testNIO();}static void testNIO() throws Exception {ExecutorService executorService = Executors.newCachedThreadPool();ServerSocket serverSocket = new ServerSocket(8888);InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 8888);SocketChannel socketChannel1 = SocketChannel.open(inetSocketAddress);SocketChannel socketChannel2 = SocketChannel.open(inetSocketAddress);Future<?> future = executorService.submit(new NIOBlock(socketChannel1));executorService.execute(new NIOBlock(socketChannel2));executorService.shutdown();TimeUnit.SECONDS.sleep(1);future.cancel(true);TimeUnit.SECONDS.sleep(1);socketChannel2.close();} }

輸出結果:

Waiting for read(): NIOBlock@5cb03462 Waiting for read(): NIOBlock@6b033b12 ClosedByInterruptException            //對應submit()提交后調用Future的cancle(true)方法。 Exiting NIOBlocked.run() NIOBlock@5cb03462 AsynchronousCloseException 對用execute()提交后調用關閉系統底層資源的close()方法 Exiting NIOBlocked.run() NIOBlock@6b033b12Process finished with exit code 0

對于?Channel?,如果通過?submit()?提交,那么可以使用?Future?的?cancel(true)?方法關閉,得到的異常是

?ClosedByInterruptException?。如果是通過?execute()?提交,那么只能使用資源的?close()?方法進行關閉,得到的異常是?AsynchronousCloseException?.

所以綜上:我們最好使用?ExecutorService?的? Future<?> submit(Runnable task);?并且使用NIO.

就像前面你在不可中斷I/O中或者等待同步鎖中所觀察到的那樣,無論任何時刻,只要任務以不可中斷的方式被阻塞,那么都有潛在的會鎖住程序的可能,但是我們直到,在JDK5中,添加以了個特性。

即在?ReentrantLock?上阻塞的任務具備可以被中斷的能力。這與?synchronized?方法或者臨界區上阻塞的任務完全不同。

例子如下:

import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;/*** Created by huaox on 2017/4/20.**/class BlockedMutex{private Lock lock = new ReentrantLock();BlockedMutex() {lock.lock();}void f(){try {lock.lockInterruptibly();//這個方法具有可被中斷的能力System.out.println("lock acquired in f()");} catch (InterruptedException e) {System.out.println("interrupted from lock acquisition in f()");}} } class Blocked2 implements Runnable{BlockedMutex mutex = new BlockedMutex();@Overridepublic void run() {System.out.println("waiting for f() in BlockedMutex");mutex.f();System.out.println("broken out of mutex call");} } public class Interrupting2 {public static void main(String[] args) throws InterruptedException {Thread thread = new Thread(new Blocked2());thread.start();TimeUnit.SECONDS.sleep(1);System.out.println("call thread.interrupt");thread.interrupt();} }

輸出結果:

waiting for f() in BlockedMutex call thread.interrupt interrupted from lock acquisition in f() broken out of mutex callProcess finished with exit code 0

可以看到使用?Lock?的?public void lockInterruptibly() throws InterruptedException?時其具有可被中斷的能力

所以我們以后最好不要使用?synchronized?而使用Lock

轉載于:https://www.cnblogs.com/soar-hu/p/6739189.html

總結

以上是生活随笔為你收集整理的java多线程基本概述(二十)——中断的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 久久久av免费 | 亚洲欧美在线观看 | 亚欧洲乱码视频 | 欧洲人妻丰满av无码久久不卡 | 日韩国产欧美一区二区 | 日韩综合久久 | www插插插| av在线第一页 | 日韩一区二区三区四区在线 | 国产精品久久久久免费 | 亚洲无遮挡 | 香蕉视频免费在线看 | 福利小视频 | 欧美成人综合视频 | 日韩性生活大片 | 影音先锋在线视频 | 好吊妞一区二区三区 | 亚洲av成人无码一区二区三区在线观看 | 夜夜天天操 | 91精产品一区观看 | 免费毛片网 | 伊人网国产 | 国产精品二区视频 | 欧美性生活一区二区三区 | 2020av视频 | 亚洲精品久久久久久久久 | 黄色一级大片在线免费看国产一 | 国产香蕉尹人视频在线 | 99热这里有| 欧美日韩在线免费播放 | 国产精品jizz在线观看美国 | av资源首页 | 曰批又黄又爽免费视频 | 男人天堂avav | 欧美日韩激情在线观看 | 国产亚洲一区二区三区 | 久操视频在线观看 | 69堂视频 | xxxx国产视频 | 日韩在线一二 | 日本熟妇色xxxxx日本免费看 | 少妇人妻在线视频 | 午夜私人影院 | 日韩在线观看视频一区二区 | 国产精品社区 | 日韩一级片在线观看 | 久久加久久 | av免费不卡 | 色老头在线观看 | 成人免费视频网址 | 欧美一级在线播放 | www.狠狠干 | 成年人在线免费 | 在线播放你懂得 | 青青草十七色 | 成人高清视频在线观看 | 国产一区二区三区四区在线观看 | 欧美一区二区网站 | 天天色天天射综合网 | 一级黄av| 久久精品8 | 请用你的手指扰乱我吧 | 婷婷激情丁香 | 中文字幕高清在线播放 | 国产高清视频在线观看 | 五月天丁香婷 | 国产成人激情视频 | 男人的天堂伊人 | 激情婷婷在线 | 亚洲精品66 | 91一二区| 欧美激情精品久久久久久免费 | 操日本老妇 | 国产中文视频 | 91中文字幕在线观看 | 国产伦一区二区 | 精品一区二区日韩 | 国产三级在线 | 一色综合 | 亚洲激情第一页 | 激情小视频| 欧美成人一区二免费视频软件 | 热精品| 拍国产真实乱人偷精品 | 日日夜夜操操 | 强行无套内谢大学生初次 | 91人人澡人人爽人人精品 | 一级黄色片网站 | 国产免费av一区二区三区 | 影音先锋中文字幕在线 | 伊人久久久久噜噜噜亚洲熟女综合 | 成人av影视在线观看 | 超级碰在线观看 | 狠狠做深爱婷婷久久综合一区 | 国产成人毛片 | 久久久视频6r | 草久久久| 豆花在线观看 | 天堂网在线最新版www中文网 |