java创建指定id线程_Java 小例子:创建和使用固定大小的线程池 | 学步园

本文介绍了Java 1.5中的固定大小线程池FixedThreadPool的使用,通过创建一个最大并发任务数为3的线程池,并演示了如何安排和管理任务执行。学习者将了解如何控制线程池的生命周期,包括调用shutdown()和awaitTermination()方法。
摘要由CSDN通过智能技术生成

Java 1.5 开始,提供了线程池供大家使用,功能还挺全的。下面是一个简单的例子。复杂的例子将放在后面几篇博客中。

import java.util.List;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

/**

* 固定大小线程池

*

* @author yiding.he

*/

public class FixedThreadPoolDemo {

public static void main(String[] args) {

// 创建一个最多同时运行 3 个任务的线程池

ExecutorService service = Executors.newFixedThreadPool(3);

// 安排若干个任务运行

service.execute(new RunnableImpl(1));

service.execute(new RunnableImpl(2));

service.execute(new RunnableImpl(3));

service.execute(new RunnableImpl(4));

service.execute(new RunnableImpl(5));

service.execute(new RunnableImpl(6));

service.execute(new RunnableImpl(7));

service.execute(new RunnableImpl(8));

service.execute(new RunnableImpl(9));

service.execute(new RunnableImpl(10));

service.execute(new RunnableImpl(11));

service.execute(new RunnableImpl(12));

service.execute(new RunnableImpl(13));

service.execute(new RunnableImpl(14));

service.execute(new RunnableImpl(15));

// 结束线程池。shutdown() 不会马上结束,而是等所有安排的任务执行完才结束。

service.shutdown();

// 如果不想马上结束,又不愿意等太长时间,那么可以调用 awaitTermination() 方法等待一段时间

try {

service.awaitTermination(5, TimeUnit.SECONDS);

System.err.println("等待时间已过");

// shutdownNow() 将放弃所有正在等待的任务,等当前执行的任务全部完成之后,结束线程池。

List abandoned = service.shutdownNow();

System.err.println("被遗弃的任务:" + abandoned);

} catch (InterruptedException e) {

e.printStackTrace();

System.exit(-1);

}

}

/

private static class RunnableImpl implements Runnable {

private int id;

private RunnableImpl(int id) {

this.id = id;

}

public void run() {

System.out.println("开始执行" + id);

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// nothing to do

}

System.out.println(id + "执行完毕。");

}

@Override

public String toString() {

return "线程" + id;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值