Java并发编程实例--12.使用线程工厂创建线程
工厂模式是面向对象编程世界中最有用的设计模式。
它是一个创新型的模式,目标是开发一个对象,这个对象的任务是去创建其他类对象。
这样一来,如果我们想创建某些类的对象就不需要使用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.使用线程工厂创建线程的更多相关文章
- Java并发编程原理与实战五:创建线程的多种方式
一.继承Thread类 public class Demo1 extends Thread { public Demo1(String name) { super(name); } @Override ...
- Java并发编程原理与实战八:产生线程安全性问题原因(javap字节码分析)
前面我们说到多线程带来的风险,其中一个很重要的就是安全性,因为其重要性因此,放到本章来进行讲解,那么线程安全性问题产生的原因,我们这节将从底层字节码来进行分析. 一.问题引出 先看一段代码 packa ...
- Java并发编程原理与实战二十一:线程通信wait¬ify&join
wait和notify wait和notify可以实现线程之间的通信,当一个线程执行不满足条件时可以调用wait方法将线程置为等待状态,当另一个线程执行到等待线程可以执行的条件时,调用notify可以 ...
- Java并发编程(一):进程和线程之由来
转自:http://www.cnblogs.com/dolphin0520/p/3910667.html 在前面,已经介绍了Java的基础知识,现在我们来讨论一点稍微难一点的问题:Java并发编程.当 ...
- Java 并发编程(四):如何保证对象的线程安全性
01.前言 先让我吐一句肺腑之言吧,不说出来会憋出内伤的.<Java 并发编程实战>这本书太特么枯燥了,尽管它被奉为并发编程当中的经典之作,但我还是忍不住.因为第四章"对象的组合 ...
- java并发编程JUC第十篇:CyclicBarrier线程同步
在之前的文章中已经为大家介绍了java并发编程的工具:BlockingQueue接口.ArrayBlockingQueue.DelayQueue.LinkedBlockingQueue.Priorit ...
- [Java 并发] Java并发编程实践 思维导图 - 第二章 线程安全性
依据<Java并发编程实践>一书整理的思维导图.
- Java并发编程的艺术笔记(八)——线程池
一.线程池的主要处理流程 ThreadPoolExecutor执行execute方法分下面4种情况. 1)如果当前运行的线程少于corePoolSize,则创建新线程来执行任务(注意,执行这一步需要获 ...
- java并发编程(十七)Executor框架和线程池
转载请注明出处:http://blog.csdn.net/ns_code/article/details/17465497 Executor框架简介 在Java 5之后,并发编程引入了一堆新的启动 ...
- Java并发编程原理与实战三十七:线程池的原理与使用
一.简介 线程池在我们的高并发环境下,实际应用是非常多的!!适用频率非常高! 有过使用过Executors框架的朋友,可能不太知道底层的实现,这里就是讲Executors是由ThreadPoolExe ...
随机推荐
- JVM大页内存的学习与使用
JVM大页内存的学习与使用 原理和背景 操作系统是计算机的重要组成部分. 现代的操作系统一般都采用 段页式内存管理. 段一般是为了管理和权限 页主要是为了虚拟内存和物理内存的映射. 分页管理可以让物理 ...
- [转帖]A Quick Look at the Huawei HiSilicon Kunpeng 920 Arm Server CPU
https://www.servethehome.com/a-quick-look-huawei-hisilicon-kunpeng-920-arm-server-cpu/ Huawei Hi ...
- [转帖]Oracle进程中的 LOCAL=NO 和 LOCAL=YES
https://www.cnblogs.com/wjoyxt/p/3780860.html 我们在服务器上用sqlplus 连接数据库,在查看进程,会多出一条记录: oracle 16007 1600 ...
- [转帖]TiDB-merge region相关问题
一.开启region merge # 控制 Region Merge 的 size 上限,当 Region Size 大于指定值时 PD 不会将其与相邻的 Region 合并 pd-ctl confi ...
- [转帖]怎么查看Linux服务器硬件信息,这些命令告诉你
https://zhuanlan.zhihu.com/p/144368206 Linux服务器配置文档找不到,你还在为查询Linux服务器硬件信息发愁吗?学会这些命令,让你轻松查看Linux服务器的C ...
- [转帖]CPU Turbo&Cstate&Pstate简介
https://www.jianshu.com/p/eaefd1eb0ac6 测试环境 CPU 1 Intel(R) Xeon(R) Gold 5218 CPU @ 2.30GHz 16 3130 3 ...
- 【转帖】15.JVM栈帧的内部结构
目录 1.栈中存储的是什么? 2.栈的运行原理 1.栈中存储的是什么? 1.每个线程都有自己的栈,栈中存储的是栈帧. 2.在这个线程上正在执行的每个方法都各自对应一个栈帧.方法与栈帧是一对一的关系. ...
- [转帖]SPEC测试arm服务器性能,SPECJVM2008测试处理器性能_服务器评测与技术-中关村在线...
首先,我们使用SPECJVM2008测试最新至强E5处理器的虚拟化性能. SPECJVM2008是一种通用的多线程Java基准测试工具,它能够反映JRE(Java Runtime Environmen ...
- CentOS创建vsftp进行读写操作的简单方法
1. 安装vsftpd yum install epel-release yum install vsftpd 2. 进入系统设置简单进行处理 注意 user_list 是不允许访问的列表. [roo ...
- axios文件上传和 Content-Type类型介绍
Content-Type的作用是什么? Content-Type: 用于在请求头部指定资源的类型和字符编码. 请求头中的content-type,就是 B端发给S端的数据类型描述 . 即告诉服务器端, ...