semaphore是java里边的信号灯,感觉很像blockqueue,嗯
package com.mutiple;
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 exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(5);
for (int i = 0; i < 20; i++) {
final int no = i;
Runnable run = new Runnable() {
@Override
public void run() {
try {
semp.acquire();
System.out.println("Accessing: "+no);
long time = (long) (Math.random()*10000);
System.out.println(time);
Thread.sleep(time);
semp.release();
System.out.println("---------------"+semp.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.execute(run);
}
exec.shutdown();
}
}
标签:java,semaphore,System,实例,简单,Semaphore,import,out,semp From: https://blog.51cto.com/u_2465818/6209747