
测试代码:
package com.kaka.thread;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class TestThreadPool {
public static void main(String[] args) {
//1.创建线程池
//newFixedThreadPool 参数为线程池大小
ExecutorService service= Executors.newFixedThreadPool(10);
//把线程丢进去,执行Runnable接口的实现类
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭连接
service.shutdown();
}
}
//Runnable接口实现的线程
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
输出结果:
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-4
Process finished with exit code 0
