多线程 主线程调用多个子线程

package com.tristan;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * http://dongxuan.iteye.com/blog/901689
 * http://dongxuan.iteye.com/blog/902571
 * @author Administrator
 *
 */
public class TestMultiThread {

	private static ThreadPoolExecutor threadPoolExecutor;
	
	static{
		threadPoolExecutor = new ThreadPoolExecutor(2, 4, 1, TimeUnit.MINUTES, 
				new ArrayBlockingQueue<Runnable>(2),
				new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ExecuteEngine-%s").build());
	}
	
	public static void main(String[] args) throws Exception{
		
		final AtomicLong ai = new AtomicLong(0);
		
		int num = 4;
		for (int i = 0; i < num; i++) {
			Worker worker = new Worker(ai);
			threadPoolExecutor.execute(worker);
		}

		while(true){
			synchronized (ai) {
				if(ai.get() == num){
					break;
				}else{
					ai.wait(1000);
				}
			}
		}
		
		
		System.out.println("end " +  ai.get());
		
	}
	
	
	static class Worker implements Runnable{
		
		AtomicLong ai;
		
		public Worker(AtomicLong ai) {
			this.ai = ai;
		}
		
		@Override
		public void run() {
			Random r = new Random();
			try {
				long time = 1000 + r.nextInt(10*1000);
				System.out.println(Thread.currentThread().getName() + "  "+time);
				Thread.sleep(time);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			ai.incrementAndGet();
			
			synchronized (ai) {
				ai.notify();
			}
		}
	}
}

猜你喜欢

转载自tristan-s.iteye.com/blog/2240418