package com.jxh.test;
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 executor = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(5);
for(int i=0; i<20; i++) {
final int index = i;
Runnable runable = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Accessing " + index);
Thread.sleep(1000l);
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executor.execute(runable);
}
executor.shutdown();
}
}
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 executor = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(5);
for(int i=0; i<20; i++) {
final int index = i;
Runnable runable = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Accessing " + index);
Thread.sleep(1000l);
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executor.execute(runable);
}
executor.shutdown();
}
}
本文介绍了一个使用Java的Semaphore类来限制并发访问数量的例子。通过创建一个固定大小的信号量并利用线程池执行任务,确保了同时最多只有五个线程可以访问资源,其余线程必须等待。
327

被折叠的 条评论
为什么被折叠?



