之前有一篇文章介绍了用thread的join()方法来实现,但是我在实际应用过程中发现了一个问题,就是当任务占用时间过长时,会导致service的超时,太杯具了,研究了下,发现也许有更好的方法,还没来得及测试,先记录。

使用Java的线程次机制。

java.util.concurrent.ThreadPoolExecutor 线程池类

我这里用到的方法是newSingleThreadExecutor,这个方法只会创建一个线程,然后所有添加的任务都会用这个线程来顺序执行。代码如下:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
ExecutorService pool = null;
public ExecutorService getSingleThreadPool() {
if (pool == null) {
pool = Executors.newSingleThreadExecutor();
}
return pool;
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService pool = ThreadPool.getSingleThreadPool();
for (int i = 0; i < 5; i++)
Thread t = new myThread(i);
pool.execute(t);
}
pool.shutdown();
}
class myThread extends Thread{
int i = 0;
public myThread(int i){
this.i = i;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行。。。" + this.i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}