Java信号量控制多线程并发

package com.uusafe.thread2;


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


public class UseSinaple {


public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();

final Semaphore eSemaphore=new Semaphore(5);

for (int i = 0; i < 20; i++) {
final int No=i;
Runnable runnable=new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
try {
eSemaphore.acquire();
System.out.println("Accessing "+No);
Thread.sleep(10000);
eSemaphore.release();
} catch (Exception e) {
// TODO: handle exception
}
}
};

executorService.execute(runnable);


}


try {
Thread.sleep(3000);

} catch (Exception e) {
// TODO: handle exception
}


}


}

猜你喜欢

转载自blog.csdn.net/douyunqian668/article/details/80381075