import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
//假若一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,
//其他工人才能继续使用。那么我们就可以通过Semaphore来实现
public static void main(String[] args) {
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
int num = 5 ;
long start = System.currentTimeMillis();
Semaphore semaphore = new Semaphore(num);
for (int i = 0; i < 8; i++) {
newFixedThreadPool.submit(new SemaphoreRunnable(semaphore));
}
long end = System.currentTimeMillis();
newFixedThreadPool.shutdown();
}
public static class SemaphoreRunnable implements Runnable{
private Semaphore semaphore;
public SemaphoreRunnable(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
long start = System.currentTimeMillis();
semaphore.acquire();
//Do some Thing
Thread.sleep(1000);
semaphore.release();
long end = System.currentTimeMillis();
System.out.println(System.currentTimeMillis() +"=========" + (end-start)/1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。
个人主页:http://knight-black-bob.iteye.com/
谢谢您的赞助,我会做的更好!