我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String args[]) throws InterruptedException { ExecutorService exe = Executors.newFixedThreadPool( 3 ); for ( int i = 1 ; i <= 5 ; i++) { exe.execute( new SubThread(i)); } exe.shutdown(); while ( true ) { if (exe.isTerminated()) { System.out.println( "結束了!" ); break ; } Thread.sleep( 200 ); } } } |
上面是主線程的代碼,創建了一個能同時執行2個線程的線程池,并投入5個線程,當5個線程都執行完畢后打印---“結束了!”字符串。
exe.shutdown();該方法在加入線程隊列的線程執行完之前不會執行。exe.isTerminated()當shutdown()或者shutdownNow()執行了之后才會執行,并返回true。
在上面的代碼中必須有exe.isTerminated()的判斷,否則在投入5個線程到線程池后會直接打印:“結束了”。不能達到我們想要的效果。
通過while(true)循環判斷exe.isTerminated()的值,為了防止過多的判斷浪費資源,可設置線程睡眠Thread.sleep(200);正是由于這個睡眠,所以當所有線程池中的線程都執行完后,有可能延遲200ms才執行"結束了"語句。這個參數越小延遲越小,結果越準確。
下面是子線程,子線程只是簡單的將數字i打印出來;
1
2
3
4
5
6
7
8
9
10
|
public class SubThread extends Thread{ private final int i; public SubThread( int i){ this .i = i; } @Override public void run(){ System.out.println(i); } } |
執行結果:
3
1
4
5
2
結束了!
成功構建 (總時間: 2 秒)
子線程執行順序不能控制,所以輸出的結果是亂序的。
補充知識:java如何禁掉反射
SecurityManager
有一個checkMemberAccess這個方法可以阻止利用反射;
如:
SecurityManager sm = new SecurityManager();
sm.checkMemberAccess(Test.class, Member.PUBLIC);
前面一個為CLASS,后面需要填一個INT值,Member.PUBLIC 代表可以訪問,
如果是PUBLIC,反射可以執行,DECLARED,反射運行時,會報錯。
SecurityManager另外一個例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
package com.jd.basic.pk.manager; import java.lang.reflect.Field; import java.security.Permission; public class UseReflection { static { try { System.setSecurityManager( new MySecurityManager()); } catch (SecurityException se) { System.out.println( "SecurityManager already set!" ); } } public static void main(String args[]) { Object prey = new Prey(); try { Field pf = prey.getClass().getDeclaredField( "privateString" ); pf.setAccessible( true ); pf.set(prey, "Aminur test" ); System.out.println(pf.get(prey)); } catch (Exception e) { System.err.println( "Caught exception " + e.toString()); } } } class Prey { @SuppressWarnings ( "unused" ) private String privateString = "privateValue" ; } class MySecurityManager extends SecurityManager { public void checkPermission(Permission perm) { if (perm.getName().equals( "suppressAccessChecks" )) { throw new SecurityException( "Can not change the permission dude.!" ); } } } |
以上這篇Java 判斷線程池所有任務是否執行完畢的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://blog.chinaunix.net/uid-29368697-id-4065665.html