import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ThreadPoolTest { static int num = 100; public static void main(String[] args) throws InterruptedException { //固定线程数量的线程池,有任务就派空闲线程去执行,多余的任务等待 //ExecutorService pool= Executors.newFixedThreadPool(3); //根据任务需要,自动创建线程,且 前面已创建的线程,空闲时,可被复用 //ExecutorService pool= Executors.newCachedThreadPool(); //单个线程,若执行期出现失败而终止此单个线程,则会建一个新线程来代替,运行任务 ExecutorService pool= Executors.newSingleThreadExecutor(); //给线程池加 10条任务 for (int j= 0; j < 10; j++) { final int task = j; pool.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (int i=0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + "--" +i + "--" + task + " of taks" + " 计数:" + (--num)); } } }); // Thread.sleep(20); } //可安排在给定的延迟后运行或定期执行的命令。 ScheduledExecutorService service = Executors.newScheduledThreadPool(3); for (int i = 0; i < 5; i++) { final int x = i; service.scheduleAtFixedRate(new Runnable() { @Override public void run() { // TODO Auto-generated method stub System.out.println("Boon " + x + " " + Thread.currentThread().getName()); } },0,2,TimeUnit.SECONDS);//延迟0秒,周期2秒 } //poor.shutdownNow();//试图马上停了所有正在执行的任务,返回任务列表 pool.shutdown();//把分配给线程池的任务都执行完,就不再等待接受新任务了, // service.shutdown(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/10714.html