- Java并發編程:核心方法與框架
- 高洪巖
- 420字
- 2019-01-03 02:34:13

1.1.4 方法acquireUninterruptibly()的使用
方法acquireUninterruptibly()的作用是使等待進入acquire()方法的線程,不允許被中斷。
先來看一個能中斷的實驗。
創建項目Semaphore_acquireUninterruptibly_1,類Service.java代碼如下:
package service; import java.util.concurrent.Semaphore; public class Service { private Semaphore semaphore = new Semaphore(1); public void testMethod() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " begin timer=" + System.currentTimeMillis()); for (int i = 0; i < Integer.MAX_VALUE / 50; i++) { String newString = new String(); Math.random(); } System.out.println(Thread.currentThread().getName() + " end timer=" + System.currentTimeMillis()); semaphore.release(); } catch (InterruptedException e) { System.out.println("線程" + Thread.currentThread().getName() + "進入了catch"); e.printStackTrace(); } } }
線程類代碼如圖1-9所示。

圖1-9 線程類代碼
運行類Run.java代碼如下:
package test; import service.Service; import extthread.ThreadA; import extthread.ThreadB; public class Run { public static void main(String[] args) throws InterruptedException { Service service = new Service(); ThreadA a = new ThreadA(service); a.setName("A"); a.start(); ThreadB b = new ThreadB(service); b.setName("B"); b.start(); Thread.sleep(1000); b.interrupt(); System.out.println("main中斷了a"); } }
程序運行的效果如圖1-10所示。

圖1-10 線程B被中斷
線程B成功被中斷。
那么不能被中斷是什么效果呢?
創建項目Semaphore_acquireUninterruptibly_2,將Semaphore_acquireUninterruptibly_1項目中的所有源代碼復制到Semaphore_acquireUninterruptibly_2中,更改Service.java文件代碼如下:
package service; import java.util.concurrent.Semaphore; public class Service { private Semaphore semaphore = new Semaphore(1); public void testMethod() { semaphore.acquireUninterruptibly(); System.out.println(Thread.currentThread().getName() + " begin timer=" + System.currentTimeMillis()); for (int i = 0; i < Integer.MAX_VALUE / 50; i++) { String newString = new String(); Math.random(); } System.out.println(Thread.currentThread().getName() + " end timer=" + System.currentTimeMillis()); semaphore.release(); } }
程序運行后的效果如圖1-11所示。

圖1-11 線程B沒有被中斷
acquireUninterruptibly()方法還有重載的寫法acquire-Uninterruptibly(int permits),此方法的作用是在等待許可的情況下不允許中斷,如果成功獲得鎖,則取得指定的permits許可個數。
推薦閱讀
- Web程序設計及應用
- Java應用與實戰
- Magento 2 Theme Design(Second Edition)
- INSTANT MinGW Starter
- FLL+WRO樂高機器人競賽教程:機械、巡線與PID
- Getting Started with NativeScript
- Java EE 7 Performance Tuning and Optimization
- HTML 5與CSS 3權威指南(第3版·上冊)
- 編程菜鳥學Python數據分析
- Node.js:來一打 C++ 擴展
- 計算機應用基礎教程(Windows 7+Office 2010)
- SpringBoot從零開始學(視頻教學版)
- Drupal 8 Development Cookbook(Second Edition)
- Python趣味創意編程
- HTML5 Boilerplate Web Development