Java Multithreading and Concurrency Library Advanced Application--14

Java
Multithreading

2018-5- 5 11.22


package cn.itcast.heima2;


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


public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final  Semaphore sp = new Semaphore(3);
for(int i=0;i<10;i++){
// new Runnable 相当于1个线程
Runnable runnable = new Runnable(){
public void run(){
try {
sp.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() + 
"进入,当前已有" + (3-sp.availablePermits()) + "个并发");
try {
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread" + Thread.currentThread().getName( ) + 
"Leaving"); sp.release(); //The following code is sometimes inaccurate because it does not synthesize the atomic unit with the above code System.out.println("Thread" + Thread.currentThread(). getName() +  "left, currently available" + (3-sp.availablePermits()) + "concurrent"); } }; service.execute(runnable); } }











}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325729346&siteId=291194637