方法一:
Thread.join()方法,親測可行,thread.join()方法
- Vector<Thread> ts = new Vector<Thread>();
- for (int i = 0; i < 200; i++) {
- Thread t = new Thread(new Runnable() {
- @Override
- public void run() {
- Counter.inc();
- }
- });
- ts.add(t);
- t.start();
- }
- for (Thread t : ts) {
- try {
- t.join();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("----------" + Counter.count);
(全部代碼見上一篇文章)
這個循環中的join的意思是:子線程排好隊,歡迎新同學main線程,main線程對着排好隊的他們說,我站你后邊,我站你后邊,我站你后邊。。。。(ts.size()次)。然后站到最后一個的后面了。恩、
方法二:
用線程池。
代碼:
- ExecutorService threadPool = Executors.newScheduledThreadPool(10);
- ExecutorService threadPool = Executors.newCachedThreadPool();
- for (int i = 0; i < 200; i++) {
- threadPool.execute(new Runnable() {
- @Override
- public void run() {
- chi.inc();
- }
- });
- }
- threadPool.shutdownNow();
- try {
- threadPool.awaitTermination(3, TimeUnit.MICROSECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("------" + chi.count);
Executors是個工廠,(工廠模式),創建出幾種不同類別的線程池。這里我用ScheduledThreadPool。(因為好使,注釋掉的那種不知為什么不管用)。
然后用shutdownNow(),這個方法是馬上停止(試圖)正在執行的任務,線程池進入STOP狀態,不再開啟正在等待的線程。
對比的,shutdown()方法是阻止等待中的進程開啟,等待所有正在執行的進程完成。
