1.結(jié)論先行
現(xiàn)在對(duì)各方法逐一進(jìn)行具體介紹。 2.interrupt()首先我們來使用一下 interrupt() 方法,觀察效果,代碼如下: public class MainTest { @Test public void test() { try { MyThread01 myThread = new MyThread01(); myThread.start(); myThread.sleep(2000); myThread.interrupt(); } catch (Exception e) { System.out.println('main catch'); e.printStackTrace(); } }}public class MyThread01 extends Thread { @Override public void run() { super.run(); for (int i = 0; i < 500;="" i++)="" {="" system.out.println('i=' + i); } }} 輸出結(jié)果參考: 可以看出,子線程已經(jīng)執(zhí)行完成了。說明 interrupt() 方法是不能讓線程停止,和我們一開始所說的那樣,它僅僅是在當(dāng)前線程記下一個(gè)停止標(biāo)記而已。 那么這個(gè)停止標(biāo)記我們又怎么知道呢?——此時(shí)就要介紹下面的 interrupted() 和 isInterrupted() 方法了。 3. interrupted() 和 isInterrupted()
這兩個(gè)方法很相似,下面我們用程序來看下使用效果上的區(qū)別吧。先來看下使用 interrupted() 的程序: @Testpublic void test() { try { MyThread01 myThread = new MyThread01(); myThread.start(); myThread.sleep(1000);// 7行: Thread.currentThread().interrupt(); // Thread.currentThread() 這里表示 main 線程 myThread.interrupt(); // myThread.interrupted() 底層調(diào)用了 currentThread().isInterrupted(true); 作用是判斷當(dāng)前線程是否為停止?fàn)顟B(tài) System.out.println('是否中斷1 ' + myThread.interrupted()); System.out.println('是否中斷2 ' + myThread.interrupted()); } catch (InterruptedException e) { System.out.println('main catch'); } System.out.println('main end');} 輸出結(jié)果參考: 由此可以看出,線程并未停止,同時(shí)也證明了 interrupted() 方法的解釋:測(cè)試當(dāng)前線程是否已經(jīng)中斷,這個(gè)當(dāng)前線程就是 main 線程,它從未中斷過,所以打印結(jié)果都是 false。 那么如何使 main 線程產(chǎn)生中斷效果呢?將上面第 8 行代碼注釋掉,并將第 7 行代碼的注釋去掉再運(yùn)行,我們就可以得到以下輸出結(jié)果: 從結(jié)果上看,方法 interrupted() 的確判斷出了當(dāng)前線程(此例為 main 線程)是否是停止?fàn)顟B(tài)了,但為什么第二個(gè)布爾值為 false 呢?我們?cè)谧铋_始的時(shí)候有說過——interrupted() 測(cè)試當(dāng)前線程是否已經(jīng)是中斷狀態(tài),執(zhí)行后會(huì)將狀態(tài)標(biāo)志清除。 因?yàn)閳?zhí)行 interrupted() 后它會(huì)將狀態(tài)標(biāo)志清除,底層調(diào)用了 isInterrupted(true),此處參數(shù)為 true 。所以 interrupted() 具有清除狀態(tài)標(biāo)記功能。 在第一次調(diào)用時(shí),由于此前執(zhí)行了 Thread.currentThread().interrupt();,導(dǎo)致當(dāng)前線程被標(biāo)記了一個(gè)中斷標(biāo)記,因此第一次調(diào)用 interrupted() 時(shí)返回 true。因?yàn)?interrupted() 具有清除狀態(tài)標(biāo)記功能,所以在第二次調(diào)用 interrupted() 方法時(shí)會(huì)返回 false。 以上就是 interrupted() 的介紹內(nèi)容,最后我們?cè)賮砜聪?isInterrupted() 方法吧。 isInterrupted() 和 interrupted() 有兩點(diǎn)不同:一是不具有清除狀態(tài)標(biāo)記功能,因?yàn)榈讓觽魅?isInterrupted() 方法的參數(shù)為 false。二是它判斷的線程調(diào)用該方法的對(duì)象所表示的線程,本例為 MyThread01 對(duì)象。 我們修改一下上面的代碼,看下運(yùn)行效果: @Testpublic void test() { try { MyThread01 myThread = new MyThread01(); myThread.start(); myThread.sleep(1000); myThread.interrupt(); // 修改了下面這兩行。 // 上面的代碼是 myThread.interrupted(); System.out.println('是否中斷1 ' + myThread.isInterrupted()); System.out.println('是否中斷2 ' + myThread.isInterrupted()); } catch (InterruptedException e) { System.out.println('main catch'); e.printStackTrace(); } System.out.println('main end');} 輸出結(jié)果參考: 結(jié)果很明顯,因?yàn)?isInterrupted() 不具有清除狀態(tài)標(biāo)記功能,所以兩次都輸出 true。 這 3 個(gè)方法介紹就到此結(jié)束了。 |
|
|