线程池常见方法
如何获取线程池对象
缓存线程池
自定义任务对象
public class MyRunnable implements Runnable{private int id;public MyRunnable(int id) {this.id = id;}@Overridepublic void run() {String name = Thread.currentThread().getName();System.out.println("线程" + name + "开始执行任务" + id);try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("线程" + name + "完成任务" + id);}@Overridepublic String toString() {return "MyTask{" +"id=" + id +'}';}
}
获取线程池对象
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();for (int i = 0; i < 100; i++) {MyRunnable myRunnable = new MyRunnable(i);cachedThreadPool.execute(myRunnable);}