标签:
1 package Thread; 2 3 import org.junit.Test; 4 5 import java.util.concurrent.Executor; 6 import java.util.concurrent.Executors; 7 import java.util.concurrent.Semaphore; 8 9 /** 10 * Created by csophys on 15/7/15. 11 */ 12 public class SemaphoreTest { 13 14 Semaphore semaphore = new Semaphore(2); 15 Executor executor = Executors.newCachedThreadPool(); 16 17 /** 18 * 信号量Demo, 19 * 注意:主线程如果结束后所有其附属的子线程也都会直接结束 20 */ 21 @Test 22 public void testSemaphore() { 23 24 for (int i = 0; i < 10; i++) { 25 executor.execute(new Runnable() { 26 public void run() { 27 try { 28 System.out.println("线程" + Thread.currentThread().getName() + "开始获取信号量"); 29 semaphore.acquire(); 30 System.out.println("线程" + Thread.currentThread().getName() + "已经获取信号量!"); 31 Thread.sleep(1000); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } finally { 35 semaphore.release(); 36 } 37 } 38 }); 39 } 40 try { 41 Thread.sleep(5000); 42 } catch (InterruptedException e) { 43 e.printStackTrace(); 44 } 45 } 46 }
标签:
原文地址:http://www.cnblogs.com/csophys/p/4649732.html