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 ...
随机推荐
- 给Hexo博客文章加密
有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top 首发博客地址 原文地址 这是个啥 首先, 这是 Hexo 生态圈中 最好的 ...
- [转帖]Oracle11g实现只读表方法
1.1 ALTER TABLE tab_name READ ONLY 参考:https://www.cnblogs.com/chinas/p/8440460.html Oracle 11g开始支持设置 ...
- [转帖]Oracle迁移到MySQL时数据类型转换问题
https://www.cnblogs.com/yeyuzhuanjia/p/17431979.html 最近在做"去O"(去除Oracle数据库)的相关工作,需要将Oracle表 ...
- [转帖]《Linux性能优化实战》笔记(25)—— 总结:Linux 性能工具速查
一. 性能工具速查 在梳理性能工具之前,首先给你提一个问题,那就是,在什么情况下,我们才需要去查找.挑选性能工具呢? 其实在我看来,只有当你想了解某个性能指标,却不知道该怎么办的时候,才会想到,&qu ...
- [转帖]Skywalking学习及整合springboot
目录 1. Skywalking概述 2. Skywalking主要功能 3. Skywalking主要特性 4. Skywalking架构简介 5. Spring Cloud与Skywalking实 ...
- Centos7把home目录下多余的空间转移到/根目录下
通过df-h发现,根目录只有32G,而home目录可用的,居然有142G.我现在想分出70G给根目录 把你需要挂载的机器的逻辑卷记住(上面的图,左边是逻辑卷,右边是虚拟磁盘) /dev/mapper/ ...
- c#时间格式转换汉字大写
把时间转换为汉字大写 public class DateTimeConvert { public static string ConvertToChineseCapital(DateTime date ...
- yum 安装失败解决思路$releasever(curl#6 - "Could not resolve host: mirrorlist.centos.org; Unknown error")
问题 公司使用刀片机的系统版本是CentOS 7.9.2009(Core),本人在重新安装虚拟机时,也使用对应的系统版本,在安装软件时,yum无法正常使用,一开始觉得,centos的release版本 ...
- 【Mysql】复合主键的索引
复合主键在where中使用查询的时候到底走不走索引呢?例如下表: create table index_test ( a int not null, b int not null, c int not ...
- LyScriptTools 调试控制类API接口手册
LyScriptTools模块中的DebugControl类主要负责控制x64dbg调试器的行为,例如获取或设置寄存器组,执行单步命令等,此类内的方法也是最常用的. 插件地址:https://gith ...