java线程池实例

 本里程演示了使用JDK自带的多线程机制的使用方法。一个简单的例程,加上注释,很好地说明了使用jdk实现线程池的方法,适合初学者入门。
  1. package com.cjt.thread.threadpool;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. public class Concurrent4ThreadPool { // 用于管理线程和提供线程服务的类
  5.     private ExecutorService exe = null;// 线程池
  6.     private static final int POOL_SIZE = 4;// 线程池的容量
  7.     public Concurrent4ThreadPool() {
  8.         exe = Executors.newFixedThreadPool(POOL_SIZE);// 创建线程池
  9.         System.out.println("the server is ready...");
  10.     }
  11.     public void server() {
  12.         int i = 0;
  13.         while (i < 100) {
  14.             exe.execute(new Worker(i));// 运行线程池
  15.             i++;
  16.         }
  17.     }
  18.     public static void main(String[] args) {
  19.         new Concurrent4ThreadPool().server();
  20.     }
  21.     class Worker implements Runnable // 工作线程,线程要完成的工作在此类中实现
  22.     {
  23.         int id;
  24.         Worker(int id) {
  25.             this.id = id;
  26.         }
  27.         public void run() {
  28.             System.out.println("task " + id + ":start");// 具体要做的事
  29.         }
  30.     }
  31. }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值