Java多线程设计模式(二)
Guarded Suspension Pattern
- public class Request {
- private Stringname;
- public Request(String name) {
- this.name = name;
- }
- public String getName() {
- returnname;
- }
- @Override
- public String toString() {
- return"[ Request " +name +" ]";
- }
- }
- public class RequestQueue {
- final private LinkedList<request>queue = new LinkedList<request>();
- public synchronizedvoid putRequest(Request request) {
- this.queue.addLast(request);
- notifyAll();
- }
- publicsynchronized Request getRequest() {
- // 多线程版本的if
- while (this.queue.size() <= 0) {
- try {
- wait();
- }catch (InterruptedException e) {
- }
- }
- return queue.removeFirst();
- }
- }
- import java.util.Random;
- public class ClientThreadextends Thread {
- private Random random;
- private RequestQueuerequestQueue;
- public ClientThread(RequestQueue requestQueue, String name,long seed) {
- super(name);
- this.requestQueue = requestQueue;
- this.random =new Random(seed);
- }
- @Override
- public void run() {
- for (int i = 0; i < 10000; i++) {
- Request request = new Request("No." + i);
- System.out.println(Thread.currentThread().getName() +" requests " + request);
- this.requestQueue.putRequest(request);
- try {
- Thread.sleep(this.random.nextInt(1000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- import java.util.Random;
- public class ServerThreadextends Thread {
- private Random random;
- private RequestQueuequeue;
- public ServerThread(RequestQueue queue, String name,long seed) {
- super(name);
- this.queue = queue;
- random =new Random(seed);
- }
- @Override
- public void run() {
- for (int i = 0; i < 10000; i++) {
- Request request = queue.getRequest();
- System.out.println(Thread.currentThread().getName() +" handles " + request);
- try {
- Thread.sleep(random.nextInt(1000));
- } catch (InterruptedException e) {
- }
- }
- }
- }
- public class Main {
- public static void main(String[] args) {
- RequestQueue queue = new RequestQueue();
- ServerThread serverThread = new ServerThread(queue,"ServerThread", 3141592l);
- ClientThread clientThread = new ClientThread(queue,"ClientThread", 6535897l);
- serverThread.start();
- clientThread.start();
- }
- }
- </request></request>
这段代码的关键在 ReqeustQueue类的getReqeust()方法,在该方法中,判断队列是否小于或等于0,如果是,那么就等待队列有数据之后在进行获取 Request对象的操作,注意这里使用的是while,而非if。Single Threaded Execution Pattern 只有一个线程可以进入临界区,其他线程不能进入,进行等待;而Guarded Suspension Pattern中,线程要不要等待,由警戒条件决定。只有RequestQueue类使用到了wait/notifyAll,Guarded Suspension Pattern的实现是封闭在RequestQueue类里的。
Balking Pattern
回,它与Guarded Suspension Pattern的区别在于Guarded Suspension
Pattern在警戒条件不成立时,线程等待,而Balking Pattern线程直接返回。我们来看代码实现:
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- public class Data {
- private final Stringfilename;
- private String content;
- privateboolean changed;
- public Data(String filename, String content) {
- this.filename = filename;
- this.content = content;
- this.changed =true;
- }
- public synchronizedvoid change(String content) {
- this.content = content;
- this.changed =true;
- }
- publicsynchronizedvoid save() {
- while (!this.changed) {
- return;
- }
- doSave();
- this.changed =false;
- }
- private void doSave() {
- System.out.println(Thread.currentThread().getName() +"calls doSave, content = "
- + this.content);
- File file = new File(filename);
- FileWriter writer = null;
- try {
- writer = new FileWriter(file, true);
- writer.write(this.content);
- } catch (IOException e) {
- } finally {
- if (writer !=null) {
- try {
- writer.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- import java.util.Random;
- public class ChangerThreadextends Thread {
- private Data data;
- private Randomrandom =new Random();
- public ChangerThread(String name, Data data) {
- super(name);
- this.data = data;
- }
- @Override
- public void run() {
- int i = 0;
- while (true) {
- i++;
- String content = "No." + i;
- this.data.change(content);
- try {
- Thread.sleep(random.nextInt(1000));
- } catch (InterruptedException e) {
- }
- this.data.save();
- }
- }
- }
- import java.util.Random;
- public class SaverThreadextends Thread {
- private Data data;
- private Randomrandom =new Random();
- public SaverThread(String name, Data data) {
- super(name);
- this.data = data;
- }
- @Override
- public void run() {
- while (true) {
- this.data.save();
- try {
- Thread.sleep(this.random.nextInt(1000));
- } catch (InterruptedException e) {
- }
- }
- }
- public static void main(String[] args) {
- Data data = new Data("data.txt","(empty)");
- new SaverThread("SaverThread", data).start();
- new ChangerThread("ChangerThread", data).start();
- }
- }
Producer-Consumer Pattern
- import java.io.Serializable;
- public class Data implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = 7212370995222659529L;
- private String name;
- public Data(String name) {
- this.name = name;
- }
- @Override
- public String toString() {
- return"[ Data name = " +this.name +" ]";
- }
- }
- import java.util.LinkedList;
- /**
- * 数据传输channel,默认大小100,可以通过构造函数定制channel的大小。channel为FIFO模型
- */
- public class Channel {
- private final LinkedList<data>buffer =new LinkedList<data>();
- private int bufferSize = 100;
- public Channel() {
- super();
- }
- public Channel(int channelSize) {
- this.bufferSize = channelSize;
- }
- /**
- * put数据到channel中,当channel的buffer大小大于或等于指定大小时,方法将进行等待
- *
- * @param data
- */
- public synchronizedvoid put(Data data) {
- while (buffer.size() >=this.bufferSize) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- this.buffer.addLast(data);
- System.out.println(Thread.currentThread().getName() +" put data " + data);
- notifyAll();
- }
- /**
- * 从channel中获取数据,当channel中没有数据时,进行等待
- *
- * @return
- */
- public synchronized Data take() {
- while (this.buffer.size() == 0) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- Data data = this.buffer.removeFirst();
- System.out.println(Thread.currentThread().getName() +" take date " + data);
- notifyAll();
- return data;
- }
- }
- import java.util.Random;
- public class ComsumerThreadextends Thread {
- private Channel channel;
- private Random random =new Random();
- public ComsumerThread(String name, Channel channel) {
- super(name);
- this.channel = channel;
- }
- @Override
- public void run() {
- while (true) {
- this.channel.take();
- try {
- Thread.sleep(random.nextInt(1000));
- } catch (InterruptedException e) {
- }
- }
- }
- }
- import java.util.Random;
- public class ProducerThreadextends Thread {
- private Channel channel;
- private Random random =new Random();
- private staticintdataNo = 0;
- public ProducerThread(String name, Channel channel) {
- super(name);
- this.channel = channel;
- }
- @Override
- public void run() {
- while (true) {
- Data data = new Data("No." + nextDataNo());
- this.channel.put(data);
- try {
- Thread.sleep(random.nextInt(1000));
- } catch (InterruptedException e) {
- }
- }
- }
- public staticsynchronizedint nextDataNo() {
- return ++dataNo;
- }
- }
- public class MainThread {
- public static void main(String[] args) {
- int channelSize = 1000;
- Channel channel = new Channel(channelSize);
- ProducerThread producer1 = new ProducerThread("Producer1", channel);
- ProducerThread producer2 = new ProducerThread("Producer2", channel);
- ComsumerThread comsumer1 = new ComsumerThread("Comsumer1", channel);
- ComsumerThread comsumer2 = new ComsumerThread("Comsumer2", channel);
- ComsumerThread comsumer3 = new ComsumerThread("Comsumer3", channel);
- producer1.start();
- producer2.start();
- comsumer1.start();
- comsumer2.start();
- comsumer3.start();
- }
- }
- </data></data>
Java多线程设计模式(二)的更多相关文章
- [温故]图解java多线程设计模式(一)
去年看完的<图解java多线程设计模式>,可惜当时没做笔记,导致后来忘了许多东西,打算再温习下这本书,顺便在这里记录一下~ 1.顺序执行.并行.并发 顺序执行:多个操作按照顺序依次执行. ...
- java多线程设计模式
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt220 java多线程设计模式 java语言已经内置了多线程支持,所有实现Ru ...
- Java多线程(二)关于多线程的CPU密集型和IO密集型这件事
点我跳过黑哥的卑鄙广告行为,进入正文. Java多线程系列更新中~ 正式篇: Java多线程(一) 什么是线程 Java多线程(二)关于多线程的CPU密集型和IO密集型这件事 Java多线程(三)如何 ...
- 简述Java多线程(二)
Java多线程(二) 线程优先级 Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行. 优先级高的不一定先执行,大多数情况是这样的. 优 ...
- Java多线程(二) —— 线程安全、线程同步、线程间通信(含面试题集)
一.线程安全 多个线程在执行同一段代码的时候,每次的执行结果和单线程执行的结果都是一样的,不存在执行结果的二义性,就可以称作是线程安全的. 讲到线程安全问题,其实是指多线程环境下对共享资源的访问可能会 ...
- java多线程系列(二)
对象变量的并发访问 前言:本系列将从零开始讲解java多线程相关的技术,内容参考于<java多线程核心技术>与<java并发编程实战>等相关资料,希望站在巨人的肩膀上,再通过我 ...
- java多线程系列(二)---对象变量并发访问
对象变量的并发访问 前言:本系列将从零开始讲解java多线程相关的技术,内容参考于<java多线程核心技术>与<java并发编程实战>等相关资料,希望站在巨人的肩膀上,再通过我 ...
- Java多线程设计模式(一)
目录(?)[-] Java多线程基础 Thread类的run方法和start方法 线程的启动 线程的暂时停在 线程的共享互斥 线程的协调 Single Threaded Execution Patte ...
- Java多线程设计模式(4)线程池模式
前序: Thread-Per-Message Pattern,是一种对于每个命令或请求,都分配一个线程,由这个线程执行工作.它将“委托消息的一端”和“执行消息的一端”用两个不同的线程来实现.该线程模式 ...
- Java总结篇系列:Java多线程(二)
本文承接上一篇文章<Java总结篇系列:Java多线程(一)>. 四.Java多线程的阻塞状态与线程控制 上文已经提到Java阻塞的几种具体类型.下面分别看下引起Java线程阻塞的主要方法 ...
随机推荐
- EMQ、Websocket、MQTT
mqtt.fx的安装和使用 https://blog.csdn.net/nicholaszao/article/details/79211965 EMO 使用说明 http://emqtt.com/d ...
- ARP数据包伪造
一台网络中的计算机,其传递到网络中的数据包的内容是完全由其软硬件逻辑决定的,软件可以操控硬件,硬件亦是一种特殊的软件,所以,接收者只根据数据包的内容,绝不可能判定此数据包的真正来源,一切都是可以伪 ...
- 关于BigDecimal类型在jsp页面中进行除法运算问题
出自:http://blog.csdn.net/u011910290/article/details/52935337 问题描述: 在项目编写过程中,发现BigDecimal在jsp中进行除法运算时, ...
- awk中printf的使用说明
printf()函数是格式化输出函数, 一般用于向标准输出设备按规定格式输出信息.在编写程序时经常会用到此函数.printf()函数的调用格式为: printf("", ); 其中 ...
- Python 调用阿里云 API 收集 ECS 数据
#!/usr/bin/env python # coding: utf-8 # author: Wang XiaoQiang ''' 功能介绍: 1.调用阿里云API,收集所有区域 ECS 信息 2. ...
- hibernate中 criteria.setProjection(Projections.rowCount()).uniqueResult()为null的Bug
在hibernate中,在查询总数时,会使用如下方法; public Integer getCount(final DetachedCriteria detachedCriteria) { ...
- flask 数据迁移
python flasky.py shell db.create_all() from app.models import User mhc = User("mhc") >& ...
- Asp.net 使用Neatupload 第三方控件上传大文件,在IIS7上无法正常工作解决
使用环境:Window Server2008 + IIS7 更改web.config配置 1.在<configSections></configSections>节内加入: & ...
- 【HDU4734】F(x) 【数位dp】
题意 先定义了一个函数F(X)=An*2^n-1+An-1*2^n-2+.....+A1*1.其中Ai为X的第i位的值.对于每组数据给出了两个整数A,B.问不超过B的数中有多少的F值是不超过F(A)的 ...
- shiro 权限集成Ehcache 配置 学习记录(二)
1.加入依赖 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-eh ...