0
点赞
收藏
分享

微信扫一扫

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

}





}



}

举报

相关推荐

0 条评论