- Java并發(fā)編程:核心方法與框架
- 高洪巖
- 297字
- 2019-01-03 02:34:15

1.1.12 多進路-多處理-多出路實驗
本實現(xiàn)的目標是允許多個線程同時處理任務,更具體來講,也就是每個線程都在處理自己的任務。
創(chuàng)建實驗用的項目Semaphore_MoreToOne_1,類Service.java代碼如下:
package service; import java.util.concurrent.Semaphore; public class Service { private Semaphore semaphore = new Semaphore(3); void sayHello() { try { semaphore.acquire(); System.out.println("ThreadName=" + Thread.currentThread().getName() + "準備"); System.out.println("begin hello " + System.currentTimeMillis()); for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "打印" + (i + 1)); } System.out.println(" end hello " + System.currentTimeMillis()); semaphore.release(); System.out.println("ThreadName=" + Thread.currentThread().getName() + "結束"); } catch (InterruptedException e) { e.printStackTrace(); } } }
線程類MyThread.java代碼如下:
package extthread; import service.Service; public class MyThread extends Thread { private Service service; public MyThread(Service service) { super(); this.service = service; } @Override public void run() { service.sayHello(); } }
運行類Run.java代碼如下:
package test.run; import service.Service; import extthread.MyThread; Public class Run { public static void main(String[] args) { Service service = new Service(); MyThread[] threadArray = new MyThread[12]; for (int i = 0; i < threadArray.length; i++) { threadArray[i] = new MyThread(service); threadArray[i].start(); } } }
程序運行結果如圖1-24所示。

圖1-24 打印循環(huán)中的內(nèi)容為亂序
運行的效果是多個線程同時進入,而多個線程又幾乎同時執(zhí)行完畢。
推薦閱讀
- Ext JS Data-driven Application Design
- Processing互動編程藝術
- Mastering Rust
- Learning Three.js:The JavaScript 3D Library for WebGL
- HTML5從入門到精通 (第2版)
- Java EE核心技術與應用
- OpenGL Data Visualization Cookbook
- 微前端設計與實現(xiàn)
- 自己動手構建編程語言:如何設計編譯器、解釋器和DSL
- Mastering ArcGIS Server Development with JavaScript
- OpenCV:Computer Vision Projects with Python
- iOS程序員面試筆試真題與解析
- Vue.js從入門到精通
- 實戰(zhàn)圖解MACD波段交易技術
- C# 4.0權威指南