jdk線程池
public interface Executor
void execute(Runnable command);
public interface ExecutorService extends Executor
List<Runnable> shutdownNow();
Future<?> submit(Runnable task);
public interface ScheduledExecutorService extends ExecutorService
public abstract class AbstractExecutorService implements ExecutorService
public class ThreadPoolExecutor extends AbstractExecutorService
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
//略
}
//利用executors建立線程池
//ExecutorService exs = Executors.newFixedThreadPool(10);
public class Executors
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
擴展線程池
public class Test {
static class MyTask implements Runnable {
public String name;
public MyTask(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("正在執行" + Thread.currentThread().getId() + "---" + name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService exs = new ThreadPoolExecutor(2, 5, 0,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()) {
@Override
protected void beforeExecute(Thread t, Runnable r) {
System.out.println("準備執行 " + ((MyTask) r).name);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
System.out.println("執行完成 " + ((MyTask) r).name);
}
@Override
protected void terminated() {
System.out.println("線程池退出");
}
};
for (int i = 0; i < 10; i++) {
MyTask t = new MyTask("task " + i);
exs.execute(t);
}
exs.shutdown();
}
}