2019独角兽企业重金招聘Python工程师标准>>>
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
/** *
- @author hxm
*/ public class TestThread { public static void main(String args[]){ //创建一个可重用固定线程数的线程池 ExecutorService pool = Executors.newFixedThreadPool(4);
//创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。
// ExecutorService pool = Executors.newSingleThreadExecutor(); //创建实现了runnable接口的对象 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //将线程放入池中进行执行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //关闭线程池 pool.shutdown(); } } class MyThread extends Thread{
@Overridepublic void run(){System.out.println(Thread.currentThread().getName()+" is running...");}
}
输出结果: pool-1-thread-1 is running... pool-1-thread-1 is running... pool-1-thread-3 is running... pool-1-thread-2 is running... pool-1-thread-4 is running...