工厂模式是面向对象编程世界中最有用的设计模式。

它是一个创新型的模式,目标是开发一个对象,这个对象的任务是去创建其他类对象。

这样一来,如果我们想创建某些类的对象就不需要使用new关键字。好处有以下几点:

1.容易改变对象的类或者创建这些对象的方式;

2.容易限制所创建的对象。例如,我们只能创建N个某类型的对象;

3.容易生成对象创建的统计数据;

Java并发API提供了ThreadFactory接口以实现一个线程对象工厂。一些并发API高级工具都使用线程工厂去创建线程。

本例中,我们将学习如何去实现ThreadFactory接口去创建线程对象。

MyThreadFactory.java
package com.dylan.thread.ch1.c12.factory;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory; /**
* Class that implements the ThreadFactory interface to
* create a basic thread factory
*
*/
public class MyThreadFactory implements ThreadFactory { // Attributes to save the necessary data to the factory
private int counter;
private String name;
private List<String> stats; /**
* Constructor of the class
* @param name Base name of the Thread objects created by this Factory
*/
public MyThreadFactory(String name){
counter=0;
this.name=name;
stats=new ArrayList<String>();
} /**
* Method that creates a new Thread object using a Runnable object
* @param r: Runnable object to create the new Thread
*/
@Override
public Thread newThread(Runnable r) {
// Create the new Thread object
Thread t=new Thread(r,name+"-Thread_"+counter);
counter++;
// Actualize the statistics of the factory
stats.add(String.format("Created thread %d with name %s on %s\n",t.getId(),t.getName(),new Date()));
return t;
} /**
* Method that returns the statistics of the ThreadFactory
* @return The statistics of the ThreadFactory
*/
public String getStats(){
StringBuffer buffer=new StringBuffer();
Iterator<String> it=stats.iterator(); while (it.hasNext()) {
buffer.append(it.next());
} return buffer.toString();
} }
Task.java
package com.dylan.thread.ch1.c12.task;

import java.util.concurrent.TimeUnit;

public class Task implements Runnable {

	@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
Main.java
package com.dylan.thread.ch1.c12.core;

import com.dylan.thread.ch1.c12.factory.MyThreadFactory;
import com.dylan.thread.ch1.c12.task.Task; /**
* Main class of the example. Creates a Thread factory and creates ten
* Thread objects using that Factory
*
*/
public class Main { /**
* Main method of the example. Creates a Thread factory and creates
* ten Thread objects using that Factory
* @param args
*/
public static void main(String[] args) {
// Creates the factory
MyThreadFactory factory=new MyThreadFactory("MyThreadFactory");
// Creates a task
Task task=new Task();
Thread thread; // Creates and starts ten Thread objects
System.out.printf("Starting the Threads\n");
for (int i=0; i<10; i++){
thread=factory.newThread(task);
thread.start();
}
// Prints the statistics of the ThreadFactory to the console
System.out.printf("Factory stats:\n");
System.out.printf("%s\n",factory.getStats()); } }

运行结果:

Starting the Threads
Factory stats:
Created thread 10 with name MyThreadFactory-Thread_0 on Sat May 05 16:34:56 CST 2018
Created thread 11 with name MyThreadFactory-Thread_1 on Sat May 05 16:34:56 CST 2018
Created thread 12 with name MyThreadFactory-Thread_2 on Sat May 05 16:34:56 CST 2018
Created thread 13 with name MyThreadFactory-Thread_3 on Sat May 05 16:34:56 CST 2018
Created thread 14 with name MyThreadFactory-Thread_4 on Sat May 05 16:34:56 CST 2018
Created thread 15 with name MyThreadFactory-Thread_5 on Sat May 05 16:34:56 CST 2018
Created thread 16 with name MyThreadFactory-Thread_6 on Sat May 05 16:34:56 CST 2018
Created thread 17 with name MyThreadFactory-Thread_7 on Sat May 05 16:34:56 CST 2018
Created thread 18 with name MyThreadFactory-Thread_8 on Sat May 05 16:34:56 CST 2018
Created thread 19 with name MyThreadFactory-Thread_9 on Sat May 05 16:34:56 CST 2018

Java并发编程实例--12.使用线程工厂创建线程的更多相关文章

  1. Java并发编程原理与实战五:创建线程的多种方式

    一.继承Thread类 public class Demo1 extends Thread { public Demo1(String name) { super(name); } @Override ...

  2. Java并发编程原理与实战八:产生线程安全性问题原因(javap字节码分析)

    前面我们说到多线程带来的风险,其中一个很重要的就是安全性,因为其重要性因此,放到本章来进行讲解,那么线程安全性问题产生的原因,我们这节将从底层字节码来进行分析. 一.问题引出 先看一段代码 packa ...

  3. Java并发编程原理与实战二十一:线程通信wait&notify&join

    wait和notify wait和notify可以实现线程之间的通信,当一个线程执行不满足条件时可以调用wait方法将线程置为等待状态,当另一个线程执行到等待线程可以执行的条件时,调用notify可以 ...

  4. Java并发编程(一):进程和线程之由来

    转自:http://www.cnblogs.com/dolphin0520/p/3910667.html 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当 ...

  5. Java 并发编程(四):如何保证对象的线程安全性

    01.前言 先让我吐一句肺腑之言吧,不说出来会憋出内伤的.<Java 并发编程实战>这本书太特么枯燥了,尽管它被奉为并发编程当中的经典之作,但我还是忍不住.因为第四章"对象的组合 ...

  6. java并发编程JUC第十篇:CyclicBarrier线程同步

    在之前的文章中已经为大家介绍了java并发编程的工具:BlockingQueue接口.ArrayBlockingQueue.DelayQueue.LinkedBlockingQueue.Priorit ...

  7. [Java 并发] Java并发编程实践 思维导图 - 第二章 线程安全性

    依据<Java并发编程实践>一书整理的思维导图.

  8. Java并发编程的艺术笔记(八)——线程池

    一.线程池的主要处理流程 ThreadPoolExecutor执行execute方法分下面4种情况. 1)如果当前运行的线程少于corePoolSize,则创建新线程来执行任务(注意,执行这一步需要获 ...

  9. java并发编程(十七)Executor框架和线程池

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/17465497   Executor框架简介 在Java 5之后,并发编程引入了一堆新的启动 ...

  10. Java并发编程原理与实战三十七:线程池的原理与使用

    一.简介 线程池在我们的高并发环境下,实际应用是非常多的!!适用频率非常高! 有过使用过Executors框架的朋友,可能不太知道底层的实现,这里就是讲Executors是由ThreadPoolExe ...

随机推荐

  1. [转帖]解Bug之路-记一次JVM堆外内存泄露Bug的查找

    https://zhuanlan.zhihu.com/p/245401095 解Bug之路-记一次JVM堆外内存泄露Bug的查找 前言 JVM的堆外内存泄露的定位一直是个比较棘手的问题.此次的Bug查 ...

  2. [转帖]Nginx 安全优化

    目录 前言 1.使用 SSL/TLS 证书 2.使用安全密钥交换机制 3.禁用旧的 SSL/TLS 协议 4.禁用 SSL/TLS 弱密码套件 5.禁用不需要的 HTTP 方法 6.防止缓冲区溢出攻击 ...

  3. [转帖]关于UNDO

    原文地址:https://www.modb.pro/db/70802?xzs= 一:请描述什么是Oracle Undo. 二:请描述UNDO的作用. 三:请谈谈你对Manual Undo Manage ...

  4. [转帖]Kafka Dashboard

    https://grafana.com/grafana/dashboards/18276-kafka-dashboard/ Kafka resource usage and consumer lag ...

  5. [转帖]Dockerfile中CMD和ENTRYPOINT命令详解

    https://www.jb51.net/article/136264.htm   Dockerfile中的ENTRYPOINT指令和CMD指令都可以设置容器启动时要执行的命令,但用途是有略微不同的. ...

  6. [转帖]【有效解决】Edge浏览器提示你的连接不是专用连接怎么办?

    https://www.xitongzhijia.net/xtjc/20230524/290887.html Win11正式版iso镜像最新(22H2新版) V2023 大小:4.22 GB类别:Wi ...

  7. 准备学习 make

    make -h用法:make [选项] [目标] ...选项: -b, -m 为兼容性而忽略. -B, --always-make 无条件制作 (make) 所有目标. -C 目录, --direct ...

  8. Oracle表数量对数据泵备份恢复速度的影响情况

    Oracle表数量对数据泵备份恢复速度的影响情况 背景 随着公司产品交付后的时间越来越久. 数据库的备份恢复速度会越来越慢. 最开始一直认为是因为数据量导致的. 但是最近发现, 如果只是将数据库表的量 ...

  9. vm-storage在全部都是新metric情况下的写入性能测试

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 vm-storage中,写入索引的性能要比写入data p ...

  10. 8.1 C++ 标准输入输出流

    C/C++语言是一种通用的编程语言,具有高效.灵活和可移植等特点.C语言主要用于系统编程,如操作系统.编译器.数据库等:C语言是C语言的扩展,增加了面向对象编程的特性,适用于大型软件系统.图形用户界面 ...