Java多线程的信号量

Java的信号量主要的作用是控制线程对资源的访问例如我一个线程池里面有100个线程等待执行,但是我允许最多同时运行5个线程,这5个线程只有其中一个线程执行完毕后,在线程池中等待的线程才能进入开始执行,我们可以这样设计程序:

/**
* 该示例展示了如何使用信号量
* @author Administrator
*
*/
public class MySemaphore { public static void main(String[] args) throws IOException, InterruptedException {
final Semaphore semaphore = new Semaphore(5);
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 20; i++) {
final int num = i;
Runnable task = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println("计算器:" + num + " 可用信号量:" + semaphore.availablePermits());
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.submit(task);
}
}
}

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPcAAADqCAIAAADxpkRBAAAS/UlEQVR4nO2dzZmDPBKESWsckNMZh7BR+NnbHjcIn/e+GfAd7MHQklrVrcYgud7TgP5apZKMMRqmf//3fzMhQzPR5WR46HIyPnQ5GR+6nIwPXU7GpwOX36/T9PP7OKbxx+/PNF3vxzR+Vu7XzjQ5v8sfvz9duvzx+zNNxcjv12kCK35mfXKYDhsOcPkiwrtdw9C0uLyXKd0SZ5vLf35+ssb8S6tWLJu/X8/g82NcLntOl284zuXT9Zpr+/H7U0gRHHqxVmZolz9+l9Xn9XGcfpCuE1ZhPYfrvvoQfyr1zv7z+9iUfoe/GupXx7LZtm074/xrb6nmdytlRmxNrVesaQM/v4+3VVIv/525X/XLGkVtTNusaO8A8olJ/SLErejrtNQGSi821F2eiXURFnL5UkE6Fpv+bYZrcz39co5QauteEd6SWbpc1PqX7fF7zTZtilP4Kg17mQNVsy+DIAbob61YRSVtvp0AJaPX1Ea0LYn2alcYcT0iIm9BwJy6OePnB27bWdXl+Y78VV5x+d+YFmVeJayW+veJV2jpoiRGVmRYp0qXr0oVP7Q2oeFxpqtqqYW62d8l88Gsz24X/G287zUqCVpTG9M26VNuKiRCiBpWSZm6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WnmM3Bv+tkac0uXLoagZVM8ql7UvNhJTj+lyX6oYRX1KWBee91vhPuhyx2x3+MxXxBqVoZUvcbl1dB362nR/Xqw8lr9Hu8disuzsnbFoQN/gclMpUD6byimbrUBPzLI7nIEflmrGjVsNQCRZJ4aB5L3Y3bgcn/EgSkHlpCiC9/aNdy0vsavLwbZMgTmyGdUWrj7y5bZfubt5/pDLq90/1uXg6iPy403P9+tyj/zU98vf+exagwOfTQJd7mO1sTbA6FP5dpAimlJqTnoNuhCMqtpiII3/KTsK7m4OwDqfqxlC1nLfKn5+tR1wFwUZH7qcjA9dTsaHLifjQ5eT8aHLyfjkXf5/QgaCLifjQ5eT8aHLyfjQ5WR8PC7/zx+fCZGQRswup8VJd9hcTouTHjG4nBYnnYK6nBYn/cK1nIwPr8vJ+PAeCxkf3i8n48PfPsn40OVkfOhyMj50ORkfupyMzz9vtC+FnN4RiwAAAABJRU5ErkJggg==" alt="" />

上一篇:TCP回射客户服务器模型(01 socket bind listen accept connect)


下一篇:jquery中val属性操作