码迷,mamicode.com
首页 > 其他好文 > 详细

SemaphoreTest

时间:2015-07-16 00:37:13      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

SemaphoreTest

标签:

原文地址:http://www.cnblogs.com/csophys/p/4649732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!