カウンタは、すべてのサブスレッドが完了するまでメインスレッドを待機させてから動作させます.

2168 ワード

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