程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Java並發工具類Semaphore應用實例,工具類semaphore

Java並發工具類Semaphore應用實例,工具類semaphore

編輯:JAVA綜合教程

Java並發工具類Semaphore應用實例,工具類semaphore


 1 package com.thread.test.thread;
 2 
 3 import java.util.Random;
 4 import java.util.concurrent.*;
 5 
 6 /**
 7  * Semaphore
 8  * Semaphore維護者一組權限,無實體權限,只是一組代表權限的數字,
 9  * 每一次執行acquire都會被阻塞,直到獲取獲取權限,
10  * 每一次執行release都會釋放權限,喚醒阻塞acquire線程
11  *
12  * Semaphore通常應用於限制資源訪問
13  *
14  *
15  * Created by windwant on 2016/5/27.
16  */
17 public class MySemaphore {
18 
19     public static void main(String[] args) {
20         Semaphore sp = new Semaphore(5, true);  //公平性 構造函數 true
21         ExecutorService es = Executors.newCachedThreadPool();
22         Random r = new Random();
23         for (int i = 0; i < 10; i++){
24             es.execute(new Needer(sp, r.nextInt(10), "needer" + i));
25         }
26         es.shutdown();
27     }
28 }
29 
30 class Needer implements Runnable{
31 
32     private Semaphore sp;
33 
34     private int seconds;
35 
36     private String neederName;
37 
38     Needer(Semaphore sp, int seconds, String neederName){
39         this.sp = sp;
40         this.seconds = seconds;
41         this.neederName = neederName;
42     }
43 
44     public void run() {
45         try{
46             sp.acquire();
47             System.out.println("needer " + neederName + " begin, need time: " + seconds + "s");
48             long b = System.currentTimeMillis();
49             for (int i = 0; i < seconds; i++) {
50                 Thread.sleep(1000);
51                 System.out.println("needer: " + neederName + "============" + i + "============");
52             }
53             long d = System.currentTimeMillis() - b;
54             System.out.println("needer " + neederName + " over, executing time: " + TimeUnit.SECONDS.convert(d, TimeUnit.MILLISECONDS));
55             sp.release();
56         } catch (InterruptedException e) {
57             e.printStackTrace();
58         }
59     }
60 }

項目地址:https://github.com/windwant/threadtest

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved