Java线程池学习

测试线程池的执行过程,配合源码分析线程池的实现原理。

注意Task方法中要加同步锁,不然会导致异步执行。

package 线程池;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class Test {
	public static void main(String[] args) {
		//ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200,TimeUnit.MILLISECONDS,
       //         new ArrayBlockingQueue(5));
		ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
		
		for (int i = 0; i < 150; i++) {
			PPTask myTask = new PPTask(i,executor);
			executor.execute(myTask);
		 
	}
	}
	
	static class PPTask implements Runnable {
		private int taskNum;
		ThreadPoolExecutor executor;
		public PPTask( int num,ThreadPoolExecutor executor) {
			this.taskNum = num;
			this.executor = executor;
		}
		
		@Override
		synchronized public void run() {
				System.out.println("正在执行task的id:" + taskNum);
				try {
					Thread.currentThread().sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("taskid:" + taskNum  +"执行完毕");
				
				
				System.out.println("线程池中线程数目:" + executor.getPoolSize()+",队列中等待执行的任务数目:"
				+ executor.getQueue().size()+",已执行玩别的任务数目:" + executor.getCompletedTaskCount());
		}
		
	}
}


你可能感兴趣的:(Java,Java线程池)