Executor类
Posted Mustr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Executor类相关的知识,希望对你有一定的参考价值。
//测试的线程
public class Record implements Runnable {
public int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;
public Record() {
};
public Record(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" + countDown + "),";
}
@Override
public void run() {
while(countDown-- > 0 ){
System.out.print(status());
Thread.yield();
}
}
}
=====================main===================
一、CachedThreadPool 执行类
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.harry.handler.Record;
public class CachedThreadPoolDemo {
public static void main(String[] args) {
//会不断的创建线程,当有已经完成任务的线程出现时会复用原来的线程。
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
executor.execute(new Record());
}
executor.shutdown();
}
}
二、FixedThreadPool 执行类
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.harry.handler.Record;
public class FixedThreadPoolDemo {
public static void main(String[] args) {
//首先要设置规定的线程数量。
ExecutorService exec = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
exec.execute(new Record());
}
exec.shutdown();
}
}
三、SingleThreadPool 执行类
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.harry.handler.Record;
public class SingleThreadExecutorDemo {
public static void main(String[] args) {
//相当于线程数量为1的 FixedThreadPool
//如果singleThreadEcecutor提交多个任务。那么这些任务会排队,
//每个任务都会在下一个任务执行之前运行介绍,所有的任务都共用一个线程。
ExecutorService exec = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
exec.execute(new Record());
}
exec.shutdown();
}
}
以上是关于Executor类的主要内容,如果未能解决你的问题,请参考以下文章
Java并发编程 - Executor框架Executor,