java中的semaphore和OP中是一样的,首先定义
信号量的大小,对于那些需要申请有限资源的
线程,先通过semaphore.acquire()来获得信号量,使用完毕在semaphore.release()来释放信号量即可,因此信号量需要传入给实现了
Runnable的类。
class="java">import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String [] args)
{
ExecutorService es=Executors.newCachedThreadPool();
Semaphore se=new Semaphore(2,true);
for(int i=0;i<5;i++)
{
es.execute(new Thread(new Person(se)));
}
es.shutdown();
}
}
class Person implements Runnable
{
private Semaphore sema=null;
public Person(Semaphore sema)
{
this.sema=sema;
}
public void run()
{
try
{
String name=Thread.currentThread().getName();
System.out.println(name+"等待进入电话亭");
sema.acquire();
System.out.println(name+"进入电话亭,打电话中。。。");
Thread.sleep(new Random().nextInt(5000));
System.out.println(name+"出电话亭");
sema.release();
}
catch (Exception e)
{
}
}
}