论坛首页 入门技术论坛

Java线程池

浏览 2802 次
锁定老帖子 主题:Java线程池
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-17  
Java多线程使用线程池效果更好, 目的如连接池.
第一个实例.
ThreadPool.java
package com.lichen.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {

  private static int produceTaskSleepTime = 2;
  private static int consumeTaskSleepTime = 2000;
  private static int produceTaskMaxNumber = 10;

  public static void main(String[] args) {
    // 构造一个线程池
     ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3,
         TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
        new ThreadPoolExecutor.DiscardOldestPolicy());

    for (int i = 1; i <= produceTaskMaxNumber; i++) {
      try {
        // 产生一个任务,并将其加入到线程池
         String task = "task@ " + i;
         System.out.println("put " + task);
         threadPool.execute(new ThreadPoolTask(task));

        // 便于观察,等待一段时间
         Thread.sleep(produceTaskSleepTime);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
}
ThreadPoolTask.java
package com.lichen.test;

public class ThreadPoolTask implements Runnable {
  // 保存任务所需要的数据
  private Object threadPoolTaskData;
  private static int consumeTaskSleepTime = 2000;

   ThreadPoolTask(Object tasks) {
    this.threadPoolTaskData = tasks;
   }

  public void run() {
    // 处理一个任务,这里的处理方式太简单了,仅仅是一个打印语句
     System.out.println("start .." + threadPoolTaskData);
    try {
      //便于观察,等待一段时间
       Thread.sleep(consumeTaskSleepTime);
     } catch (Exception e) {
       e.printStackTrace();
     }
     threadPoolTaskData = null;
   }

  public Object getTask() {
    return this.threadPoolTaskData;
   }
}
-------------------------------------------------------
第二个实例.
TestThreadPool.java
package com.lichen.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadPool {
  public static void main(String args[]) throws InterruptedException {
    //只有2个线程
     ExecutorService exec = Executors.newFixedThreadPool(2);
    for (int index = 0; index < 100; index++) {
       Runnable run = new Runnable() {
        public void run() {
          long time = (long) (Math.random() * 1000);
           System.out.println("Sleeping " + time + "ms");
          try {
             Thread.sleep(time);
           } catch (InterruptedException e) {
             e.printStackTrace();
           }
         }
       };
       exec.execute(run);
     } // must shutdown
     exec.shutdown();
   }
}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics