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