- package com.kxg_05;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- /*
- *
- * 线程池:
- * JDK5以后新增一个Execuors工厂类产生线程池
- * 好处:
- * 线程池里面的每一个线程代码结束后,并不会死亡,而是再次回到线程池中称为空闲状态,等待下一个对象使用
- *
- * 实现线程池代码:
- * 1.创建一个线程池,指定控制几个线程
- * public static ExecutorService newFixedThreadPool(int nThreads)
- * 2.线程池可以操作线程
- * Runnable接口实现类和Callable接口实现类
- * 3.怎么把线程添加到线程池中
- * 由于线程池是ExecutorService类,调用以下方法添加
- * <T> Future<T> submit(Callable<T> task):添加Callable实现类
- * Future<?> submit(Runnable task):添加Runnable实现类
- * 4.结束线程
- * void shutdown()
- */
- public class ExecutorsDemo {
- public static void main(String[] args) {
- // public static ExecutorService newFixedThreadPool(int
- // nThreads):创建一个指定容量的线程池
- ExecutorService pool = Executors.newFixedThreadPool(2);
- // 添加线程,Future<?> submit(Runnable task)
- MyRunnable mr1 = new MyRunnable();
- MyRunnable mr2 = new MyRunnable();
- pool.submit(mr1);
- pool.submit(mr2);
- // 结束线程
- pool.shutdown();
- }
- }
复制代码- package com.kxg_05;
- public class MyRunnable implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < 100; i++) {
- System.out.println(Thread.currentThread().getName() + ":" + i);
- }
- }
- }
复制代码
|
|