线程池newFixedThreadPool的使用
ThreadPool
A simple C++11 Thread Pool implementation
项目地址:https://gitcode.com/gh_mirrors/th/ThreadPool
免费下载资源
·
新的线程加入后,如果正在运行的线程达到了上限,则会阻塞,直到有了空闲的线程来运行。
- import java.util.Random;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- /**
- * 线程池newFixedThreadPool的使用。
- *
- * @author 赵学庆,Java世纪网(java2000.net)
- *
- */
- public class ExecutorTest {
- public static void main(String args[]) {
- Random random = new Random();
- // 建立一个容量为3的固定尺寸的线程池
- ExecutorService executor = Executors.newFixedThreadPool(3);
- // 判断可是线程池可以结束
- int waitTime = 500;
- for (int i = 0; i < 10; i++) {
- String name = "线程 " + i;
- int time = random.nextInt(1000);
- waitTime += time;
- Runnable runner = new ExecutorThread(name, time);
- System.out.println("增加: " + name + " / " + time);
- executor.execute(runner);
- }
- try {
- Thread.sleep(waitTime);
- executor.shutdown();
- executor.awaitTermination(waitTime, TimeUnit.MILLISECONDS);
- } catch (InterruptedException ignored) {
- }
- }
- }
- class ExecutorThread implements Runnable {
- private final String name;
- private final int delay;
- public ExecutorThread(String name, int delay) {
- this.name = name;
- this.delay = delay;
- }
- public void run() {
- System.out.println("启动: " + name);
- try {
- Thread.sleep(delay);
- } catch (InterruptedException ignored) {
- }
- System.out.println("完成: " + name);
- }
- }
GitHub 加速计划 / th / ThreadPool
7.74 K
2.22 K
下载
A simple C++11 Thread Pool implementation
最近提交(Master分支:2 个月前 )
9a42ec13 - 9 年前
fcc91415 - 9 年前
更多推荐
已为社区贡献4条内容
所有评论(0)