原创

java.util.concurrent解读,自定义线程工厂,线程池

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://xxlcube.blog.csdn.net/article/details/8229963

自定义线程工厂

package thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class MyThreadFactory implements ThreadFactory {

	private final ThreadGroup threadGroup;
	
	private final AtomicInteger threadNumber = new AtomicInteger(0);
	
	private final String threadPrefix;
	
	public MyThreadFactory(String name) {
		//如果已经为当前应用程序建立了安全管理器,则返回此安全管理器;否则,返回 null
		SecurityManager security = System.getSecurityManager();
		//security.getThreadGroup()调用此方法时,返回所有新创建的线程实例化后所在的线程组。默认情况下,
		//返回当前线程所在的线程组。应该由指定的安全管理器重写此方法,以返回适当的线程组。
		threadGroup = (security!=null)?security.getThreadGroup():Thread.currentThread().getThreadGroup();
		threadPrefix = name + "-thread-";
	}
	
	public Thread newThread(Runnable target) {
		//以原子方式将当前值+1,最后一个参数指定线程的堆栈大小
		Thread thread = new Thread(threadGroup,target,threadPrefix+threadNumber.getAndIncrement(),0);
		//设置为非守护级线程
		//守护级线程不属于程序的核心部分,当所有非守护级线程运行结束时,程序也就结束了
		//只要还有非守护级线程存在,程序就不能结束
		if(thread.isDaemon()) {
			thread.setDaemon(false);
		}
		if(thread.getPriority()!=Thread.NORM_PRIORITY) {
			thread.setPriority(Thread.NORM_PRIORITY);
		}
		System.out.println("执行了线程工厂的newThread()方法");
		System.out.println("线程名:"+thread.getName()+",线程组:"+thread.getThreadGroup());
		return thread;
	}


}
自定义线程池

package thread;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyThreadPool {

	//定义线程池,用给定的初始参数和默认被拒绝的执行处理程序创建新的 ThreadPoolExecutor
	//corePoolSize - 池中所保存的线程数,包括空闲线程。
	//maximumPoolSize - 池中允许的最大线程数。
	//keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
	//unit - keepAliveTime 参数的时间单位。
	//workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。
	//factory - 指定线程工厂
	//handler - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。 
	private static ThreadPoolExecutor poolExe = new ThreadPoolExecutor(1,2,0,TimeUnit.SECONDS,
			new SynchronousQueue<Runnable>(),new MyThreadFactory("MyThreadFactory"),new ThreadPoolExecutor.AbortPolicy());
	
	//获取ThreadPoolExecutor,调用execute()方法,传入一个实现Runnable接口的实现类即可
	public static ThreadPoolExecutor getExe() {
		return poolExe;
	}
}
Task类

package thread;

public class Task implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Task类中的run方法!");
	}

}
Main

package thread;

import java.io.File;
import java.util.Vector;
import java.util.concurrent.ThreadPoolExecutor;


public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadPoolExecutor tpe = MyThreadPool.getExe();
		Vector v = new Vector<Task>();
		int i=0;
		while(i<10) {
			Task task = new Task();
			tpe.execute(task);
			i++;
		}
	}

}
结果

执行了线程工厂的newThread()方法
线程名:MyThreadFactory-thread-0,线程组:java.lang.ThreadGroup[name=main,maxpri=10]
执行了线程工厂的newThread()方法
线程名:MyThreadFactory-thread-1,线程组:java.lang.ThreadGroup[name=main,maxpri=10]
Task类中的run方法!
Task类中的run方法!
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task thread.Task@20f5e814 rejected from java.util.concurrent.ThreadPoolExecutor@321ea24[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 1]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor.reject(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor.execute(Unknown Source)
	at thread.Main.main(Main.java:17)























文章最后发布于: 2012-11-27 14:25:55
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 酷酷鲨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览