计数器让主线程等待所有子线程完成后,再工作
public class ThreadPool { private static ExecutorService executor; private static int count = 0; static { executor = Executors.newFixedThreadPool(3); } public static void execute(Runnable run) { count++; executor.execute(run); } public static void close(){ executor.shutdown(); } public static boolean isClosed(){ if(executor.isShutdown()){ return true; }else{ return false; } } public synchronized static void deleteCount(){ count--; System.out.println(count); } public static int getCount(){ return count; } public static void out(){ System.out.println("最终的个数" + count); }}
?
?
public class ThreadPoolTest { public static void main(String[] args){ for(int i = 0; i< 5; i++){ ThreadPool.execute(new Runnable(){ public void run() { System.out.println(Thread.currentThread().getName() + "开始了"); try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(ThreadPoolTest.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(Thread.currentThread().getName() + "完成了"); ThreadPool.deleteCount(); } }); } while(ThreadPool.getCount() != 0){ if(ThreadPool.getCount() == 0){ break; } } System.out.println("全部完成了,结束"); ThreadPool.close(); }}
?