您的位置:首页 > 其它

用Semaphore来模拟3个位置供10个人用的问题

2015-03-28 19:02 525 查看
package com.example.semaphore;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

public static void main(String[] args){



ExecutorService service = Executors.newCachedThreadPool();

final Semaphore s = new Semaphore(3);

for (int i = 0; i < 10; i++) {

Runnable runnable = new Runnable(){

@Override

public void run() {

// TODO Auto-generated method stub

try {

s.acquire();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(3-s.availablePermits());

s.release();

System.out.println(3-s.availablePermits());

}

};

service.execute(runnable);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐