首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

计数器让主线程等候所有子线程完成后,再工作

2012-08-10 
计数器让主线程等待所有子线程完成后,再工作public class ThreadPool {private static ExecutorService ex

计数器让主线程等待所有子线程完成后,再工作

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();            }}

?

热点排行