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 ...
随机推荐
- ONVIF网络摄像头(IPC)客户端开发—RTSP RTCP RTP加载AAC音频流
前言: RTSP,RTCP,RTP一般是一起使用,在FFmpeg和live555这些库中,它们为了更好的适用性,所以实现起来非常复杂,直接查看FFmpeg和Live555源代码来熟悉这些协议非常吃力, ...
- [转帖]细说:Unicode, UTF-8, UTF-16, UTF-32, UCS-2, UCS-4
https://www.cnblogs.com/malecrab/p/5300503.html 1. Unicode与ISO 10646 全世界很多个国家都在为自己的文字编码,并且互不想通,不同的语言 ...
- Oracle session的sid与serial的简单学习
Oracle session的sid与serial的简单学习 ITPUB vage的说法 这样说吧,Oracle允许的会话数(或者说连接数)是固定的,比如是3000个.假设每个会话要占1K字节,哪一共 ...
- [转帖]db file sequential read-数据文件顺序读取
https://www.cnblogs.com/xibuhaohao/p/9959593.html 等待事件: "db file sequential read" Referenc ...
- [转帖]Windows平台下使用 Rclone 挂载 OneDrive 为本地硬盘
https://zhuanlan.zhihu.com/p/139200172 Rclone (rsync for cloud storage) 是一个命令行程序,用于同步文件和目录,支持常见的 Ama ...
- [转帖]CPU Turbo&Cstate&Pstate简介
https://www.jianshu.com/p/eaefd1eb0ac6 测试环境 CPU 1 Intel(R) Xeon(R) Gold 5218 CPU @ 2.30GHz 16 3130 3 ...
- 国产CPU制造工艺与部分性能总结
国产CPU制造工艺与部分性能总结 背景 最近一段时间验证了很多国产CPU的性能. 感觉很多地方与之前的理解有一些偏差. 前几天总结了部分架构和指令集相关的差异 今天想着总结一下制造相关的部分. 希望能 ...
- [转帖]/etc/profile和/etc/environment的区别
时间 2019-11-07 标签 profile environment 区别 繁體版 原文 https://my.oschina.net/u/2885925/blog/2989579 /etc ...
- true=='true'这个等式成立吗?
在localStorage存入里面的数据是字符串,如果你存入了一个值是Boolean类型的, 那你你取出来就是一个字符串 'true' 或者 'false' 假设取出来的值是 'true' 在你进行i ...
- Python 潮流周刊#22:Python 3.12.0 发布了!!
你好,我是猫哥.这里每周分享优质的 Python.AI 及通用技术内容,大部分为英文.标题取自其中一则分享,不代表全部内容都是该主题,特此声明. 本周刊由 Python猫 出品,精心筛选国内外的 25 ...