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

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

这样一来,如果我们想创建某些类的对象就不需要使用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. [转帖]Prometheus Shell Exporter

    Shell Exporter can execute Powershell or Bash scripts and transform its output to Prometheus metrics ...

  2. [转帖]Datadog 能成为最大的云监控厂商吗

    https://xie.infoq.cn/article/901cfd6b284e3e103ac70aeb3 作者:睿象云 2021-03-25 本文字数:2256 字 阅读完需:约 7 分钟   D ...

  3. [转帖]Linux设备与内存单位-扇区、块、段、页(sector、block、segment、page)

    每个概念是对不同的对象而言的,但它们有一定的联系 这些概念的分析背景是Linux下的内存页和磁盘结构 扇区 是硬盘等存储设备传送单位,大小一般为512B 块 是VFS和文件系统的传送单位(所以相关设备 ...

  4. [转帖]如何优雅的使用 Systemd 管理服务

    https://zhuanlan.zhihu.com/p/271071439 背景:我们在构建 Kubernetes 容器化平台时,会在节点上部署各种 agent ,虽然容器化当道的今天很多程序可以直 ...

  5. [转贴]细说:Unicode, UTF-8, UTF-16, UTF-32, UCS-2, UCS-4

    细说:Unicode, UTF-8, UTF-16, UTF-32, UCS-2, UCS-4 https://www.cnblogs.com/malecrab/p/5300503.html 1. U ...

  6. SQL注入payload学习整理

    SQLserver 用的payload 0101%'and 1=(select @@version) and '%'=' GS的一个客户端参数 <add PropertyName="F ...

  7. sed 删除部分行以及删除包含某些行的命令

    sed的简单学习 前言: 最近进行mysql数据库的备份恢复操作,发现source 命令执行时数据库表的速度非常缓慢, 本来想通过这种方式处理一下,能够减少数据备份的处理. 删除包含内容的信息 sed ...

  8. 每日一道Java面试题:Java是值传递还是引用传递?

    写在开头 Java是值传递还是引用传递?这个问题几乎100%的出现在了各大主流Java面试题中,知识点很小,但很考验面试者对于Java运行的理解,今晚趁着生产投产的空子,过来小聊一下. 实参与形参 所 ...

  9. centos7下安装postgresql-10.3

    centos7下安装pgsql10.3 前言 下载pgsql-10.3 安装 解压 安装基本的工具 编译 安装 创建目录 data.log 加入系统环境变量 增加用户 postgres 并赋权 初始化 ...

  10. 3.6 Windows驱动开发:内核进程汇编与反汇编

    在笔者上一篇文章<内核MDL读写进程内存>简单介绍了如何通过MDL映射的方式实现进程读写操作,本章将通过如上案例实现远程进程反汇编功能,此类功能也是ARK工具中最常见的功能之一,通常此类功 ...