多线程

http://www.java3z.com/cwbwebhome/article/article2/2875.html

二、一般用法举例

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TestThreadPool {
 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(3),new ThreadPoolExecutor.CallerRunsPolicy());
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();
  }
}
}
/**
线程池执行的任务 
@author hdpan 
*/
public static class ThreadPoolTask implements Runnable,Serializable{
  private static final long serialVersionUID = 0;
  //保存任务所需要的数据
  private Object threadPoolTaskData;
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;
}
}
}



http://heipark.iteye.com/blog/1156011


  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();  
  5.         ThreadPoolExecutor executor = new ThreadPoolExecutor(361, TimeUnit.DAYS, queue);  
  6.   
  7.         for (int i = 0; i < 20; i++) {  
  8.             final int index = i;  
  9.             executor.execute(new Runnable() {  
  10.                 public void run() {  
  11.                     try {  
  12.                         Thread.sleep(4000);  
  13.                     } catch (InterruptedException e) {  
  14.                         e.printStackTrace();  
  15.                     }  
  16.                     System.out.println(String.format("thread %d finished", index));  
  17.                 }  
  18.             });  
  19.         }  
  20.         executor.shutdown();  
  21.     }  
  22. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值