ForkJoinPool中的public void shutdown()方法与shutdownNow()方法
1 package Nine_showdowan_Demo; 2 3 public class MyRunnable implements Runnable { 4 5 @Override 6 public void run() { 7 8 try { 9 System.out.println("begin " + Thread.currentThread().getName() + " " + System.currentTimeMillis()); 10 Thread.sleep(4000); 11 System.out.println("end " + Thread.currentThread().getName() + " " + System.currentTimeMillis()); 12 } catch (InterruptedException e) { 13 e.printStackTrace(); 14 } 15 16 } 17 18 }
1 package Nine_showdowan_Demo; 2 3 import java.util.concurrent.ForkJoinPool; 4 5 public class Test1 { 6 7 public static void main(String[] args) throws InterruptedException { 8 9 MyRunnable mr = new MyRunnable(); 10 ForkJoinPool pool = new ForkJoinPool(); 11 pool.submit(mr); 12 Thread.sleep(1000); 13 pool.shutdown(); 14 System.out.println("main end"); 15 Thread.sleep(Integer.MAX_VALUE); 16 } 17 }
运行结果:

虽然调用了shutdown方法,但是任务依然正常运行,不受影响
(2)在调用shutdown方法后再执行一次任务

运行结果:

可以看到出现了异常,对ForkJoinPool对象调用shutdown()方法后再执行任务时,会出现异常,新添加进的进程马上被销毁,而正在运行的线程任务也被销毁了。
为防止在关闭pool后再运行任务,可以加入一个判断来解决进程意外销毁的问题:
1 package Nine_showdowan_Demo; 2 3 import java.util.concurrent.ForkJoinPool; 4 5 public class Test3{ 6 7 public static void main(String[] args) throws InterruptedException { 8 9 MyRunnable mr = new MyRunnable(); 10 ForkJoinPool pool = new ForkJoinPool(); 11 pool.submit(mr); 12 Thread.sleep(1000); 13 pool.shutdown(); 14 15 //添加一个判断,解决进程意外销毁的问题 16 if(pool.isShutdown()==false){ 17 pool.submit(mr); 18 } 19 20 System.out.println("main end"); 21 Thread.sleep(Integer.MAX_VALUE); 22 } 23 }
运行结果;

总结:
此外还可以看出,shutdown()方法不具中断的效果,就是说它遇到MyRunnable.java类中的sleep()方法并没有发生中断异常。
2.shutdownNow()方法
总结:
(1)shutdown()
每个任务正常运行直到结束;
池关闭后不再允许有新任务被执行,若有,则会抛出RejectedExecutionException异常
(2)shutdownNow结合IsInterrupted()==true判断:
立即停止当前正在执行的任务;
池关闭后不再允许有新任务执行,若有,则会抛出RejectedExecutionException异常
(2)shutdownNow结合IsInterrupted()==false判断:
每个任务正常运行直到结束;
池关闭后不再允许有新任务执行,若有,则会抛出RejectedExecutionException异常。

浙公网安备 33010602011771号