Semaphore关于抢车位例子


package com.test;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest
{

/**
* @param args
*/
public static void main(String[] args)
{
ExecutorService pool = Executors.newCachedThreadPool();
final Semaphore sp = new Semaphore(3); // 3个车位
for (int i = 0; i < 10; i++)
{
pool.execute(new Runnable()
{
public void run()
{
try
{
sp.acquire();
System.out.println("小车:" + Thread.currentThread().getName()
+ "已抢到车位,还有"+sp.availablePermits()+"个车位");
Thread.sleep(new Random().nextInt(10000));
sp.release();
System.out.println("小车:" + Thread.currentThread().getName()
+ "离开车位,还有"+sp.availablePermits()+"个车位");
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
pool.shutdown();
}

}

你可能感兴趣的:(多线程)