目录
序言
一、主程序
二、自定义线程
三、线程工厂
四、普通任务
五、执行结果
序言
线程工厂的目标是可以创建统一的线程对象:
- 实现自定义的线程类
- 实现ThreadFactory接口,来实现工厂类
- 使用工厂来创建线程对象
一、主程序
package xyz.jangle.thread.test.n8_4.threadfactory;/*** 8.4、实现线程工厂(ThreadFactory)* * @author jangle* @email jangle@jangle.xyz* @time 2020年9月22日 下午5:19:57* */
public class M {public static void main(String[] args) throws Exception {// 1、创建线程工厂var factory = new MyThreadFactory("jangle");// 2、创建普通任务var task = new MyTask();// 3、使用工厂创建线程Thread thread = factory.newThread(task);thread.start();thread.join();System.out.println("M: 线程信息:"+thread);System.out.println("M: 结束");}}
二、自定义线程
package xyz.jangle.thread.test.n8_4.threadfactory;import java.util.Date;/*** 自定义的线程* @author jangle* @email jangle@jangle.xyz* @time 2020年9月22日 下午5:22:24* */
public class MyThread extends Thread {private final Date creationDate;private Date startDate;private Date finishDate;public MyThread(Runnable r, String name) {super(r, name);creationDate = new Date();}@Overridepublic void run() {setStartDate(new Date());super.run();setFinishDate(new Date());}public void setStartDate(Date startDate) {this.startDate = startDate;}public synchronized void setFinishDate(Date finishDate) {this.finishDate = finishDate;}public synchronized long getExecutionTime() {return finishDate.getTime() - startDate.getTime();}@Overridepublic synchronized String toString() {StringBuffer buffer = new StringBuffer();buffer.append(getName());buffer.append(": ");buffer.append(" Create :");buffer.append(creationDate);buffer.append(": Running time : ");buffer.append(getExecutionTime());buffer.append(" Milliseconds.");return buffer.toString();}}
三、线程工厂
package xyz.jangle.thread.test.n8_4.threadfactory;import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;/*** 线程工厂* @author jangle* @email jangle@jangle.xyz* @time 2020年9月22日 下午5:41:43* */
public class MyThreadFactory implements ThreadFactory {private AtomicInteger counter;private String prefix;public MyThreadFactory(String prefix) {super();this.prefix = prefix;counter = new AtomicInteger(1);}@Overridepublic Thread newThread(Runnable r) {var t = new MyThread(r, prefix + "-" + counter.getAndIncrement());return t;}}
四、普通任务
package xyz.jangle.thread.test.n8_4.threadfactory;import java.util.concurrent.TimeUnit;/*** 一个普通任务* @author jangle* @email jangle@jangle.xyz* @time 2020年9月22日 下午5:45:12* */
public class MyTask implements Runnable {@Overridepublic void run() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}}}
五、执行结果
M: 线程信息:jangle-1: Create :Tue Sep 22 17:48:12 CST 2020: Running time : 2001 Milliseconds.
M: 结束