`
chxiaowu
  • 浏览: 235073 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

JAVA多线程设计模式三 Guarded Suspension Pattern

 
阅读更多

一定要满足的条件  Guard Condition ,警戒条件。

 

public class Request {
    private final String name;
    public Request(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public String toString() {
        return "[ Request " + name + " ]";
    }
}

 

 

 

public class RequestQueue {
    private final LinkedList queue = new LinkedList();
    public synchronized Request getRequest() {
        while (queue.size() <= 0) {
            try {                                   
                wait();
            } catch (InterruptedException e) {      
            }                                       
        }                                           
        return (Request)queue.removeFirst();
    }
    public synchronized void putRequest(Request request) {
        queue.addLast(request);
        notifyAll();
    }
}

 

 

public class ClientThread extends Thread {
    private Random random;
    private RequestQueue requestQueue;
    public ClientThread(RequestQueue requestQueue, String name, long seed) {
        super(name);
        this.requestQueue = requestQueue;
        this.random = new Random(seed);
    }
    public void run() {
        for (int i = 0; i < 10000; i++) {
            Request request = new Request("No." + i);
            System.out.println(Thread.currentThread().getName() + " requests " + request);
            requestQueue.putRequest(request);
            try {
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
            }
        }
    }
}

 

 

public class ServerThread extends Thread {
    private Random random;
    private RequestQueue requestQueue;
    public ServerThread(RequestQueue requestQueue, String name, long seed) {
        super(name);
        this.requestQueue = requestQueue;
        this.random = new Random(seed);
    }
    public void run() {
        for (int i = 0; i < 10000; i++) {
            Request request = requestQueue.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 requestQueue = new RequestQueue();
        new ClientThread(requestQueue, "Alice", 3141592L).start();
        new ServerThread(requestQueue, "Bobby", 6535897L).start();
    }
}

 

 

理解为 带条件的同步关键字。 wait / notify

 

 

1、while(!ready){
      wait();
}

ready = true;
notifyAll();

2、while(!ready){
     Thread.yield();
}


ready=true;

 

注:Thread.yield(); 不会解除锁定,所以这句不应该放在同步关键字中。 ready 声明为 volatile

分享到:
评论
1 楼 zerozone2011 2017-01-04  
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Bluce handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Bluce handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Bluce handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Bluce handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Bluce handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Cool handles [Request No.0 ] queue size:0
2017-01-04 17:05:26 Diet handles [Request No.0 ] queue size:0

有问题呀 我就生成一个request,然后三个消费者消费,按说不应该都等待啦吗?可是linkedlist没有清空,getRequest依旧可以拿到数据,而实际打印的时候linkedlist的size确实为空了呀

相关推荐

    java多线程设计模式详解(PDF及源码)

    书中包含Java线程的介绍导读、12个重要的线程设计模式和全书总结以及丰富的附录内容。第一章相关线程设计模式的介绍,都举一反三使读者学习更有效。最后附上练习问题,让读者可以温故而知新,能快速地吸收书中的...

    java多线程设计模式 (PDF中文版, 附源码)

    目录: 漫谈UML Introduction 1 Java语言的线程 Introduction 2 多线程...总结 多线程程序设计的模式语言 附录A 练习问题的解答 附录B Java的内存模型 附录C Java线程的优先级 附录D 线程相关的主要API 附录E 参考文献

    Java多线程详解

    Java多线程模式详解 目录: 一、漫谈UML Java语言的线程 多线程的评量标准 二、 1、Single Threaded Execution ———— 能通过这座桥的,只有一个人 2、Immutable ———— 想破坏它也没办法 3、Guarded ...

    36种最新设计模式整理

    Guarded Suspension 模式 Producer Consumer 模式 Worker Thread 模式 Thread-Per-Message 模式 Future 模式 Read-Write-Lock 模式 Two-phase Termination 模式 Thread-Specific Storage 模式

    汪文君高并发编程实战视频资源全集

    │ 高并发编程第二阶段41讲、多线程设计模式内容回顾与总结.mp4 │ 高并发编程第二阶段42讲、ClassLoader课程大纲介绍.mp4 │ 高并发编程第二阶段43讲、类加载的过程以及类主动使用的六种情况详细介绍.mp4 │ 高...

    汪文君高并发编程实战视频资源下载.txt

    │ 高并发编程第二阶段41讲、多线程设计模式内容回顾与总结.mp4 │ 高并发编程第二阶段42讲、ClassLoader课程大纲介绍.mp4 │ 高并发编程第二阶段43讲、类加载的过程以及类主动使用的六种情况详细介绍.mp4 │ 高...

    laravel中的fillable和guarded属性详解

    今天小编就为大家分享一篇laravel中的fillable和guarded属性详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    guarded-array:边界检查数组

    var guard = require ( 'guarded-array' ) //First create any old array var array = [ 0 , 1 , 2 , 3 , 4 , 5 ] //Then we protect it using guard! var guardedArray = guard ( array ) //The guarded array ...

    guarded-string:防止在应用程序中意外地在字符串中引入XSSKong

    yarn add guarded-string 用法 重要的! 应该将其用于防止XSS攻击之类的东西,而不是用于隐藏敏感信息。 import guardedString from 'guarded-string' ; const myString = guardedString `My very important (but ...

    guarded-bayou-7383

    JAX-RS 模板应用程序这是使用 JAX-RS 的轻量级 RESTful API 的模板。...在本地运行应用程序首先构建: $mvn clean install然后运行它: $ java -cp target/classes:target/dependency/* com.example.Main

    scalac-guardedblocks-plugin:简单的Scala编译器插件

    scalac-guardedblocks-plugin 简单的Scala编译器插件

    程序语言设计原理习题解答

    8.5 Guarded Commands 367 8.6 Conclusions 371 Summary • Review Questions • Problem Set •Programming Exercises 372 Chapter 9 Subprograms 377 9.1 Introduction 378 9.2 Fundamentals of ...

    节律

    我们遵循使用Node和MySQL的MVC设计模式来查询和路由应用程序中的数据。 把手用于生成HTML。 Travis CI用于配置棉绒并进行连续的分割。然后将该项目加载到heroku中,以与JawsDB MySQL附加组件一起用作数据库。目录...

    GuardedCommands:用于模拟防护命令语言的Python程序

    ] 可以串联多个语句,并且最后一个语句后不能跟分号。 依次执行两个语句分配(:=) [; ] := &lt;expression&gt;[; &lt;expression&gt;] 将左侧的变量替换为右侧的值在右侧,不仅可以使用简单的数字,而且可以使用...

    butterknife 8.8.0

    When specified as false, checks for required views being non-null are elided and casts are no longer guarded with user-friendly error messages. This reduces the amount of generated code for release ...

    AsyncDebounce:防止在异步操作正在进行时多次调用异步函数

    防止在异步操作正在进行时多次调用异步函数。 操作完成后,将进行操作进行时对该函数的最后一次调用。 中间调用将丢失,如果在异步操作正在进行时没有进行调用,则不会再次调用该函数。 这种去抖动不是基于时间,...

    Understanding_Ipv6

    These details are highly guarded Microsoft intellectual property that is of interest only to a relative handful of software developers. The purpose of this book is to provide an educational vehicle...

    [Photoshop.CS4.炫招].(Photoshop.CS4.Down.&.Dirty.Tricks).[美]Scott.Kelby.完美版.pdf

    You’ll learn some of the most closely guarded Photoshop CS4 special effects—the same ones you see on TV, in magazines, and on the Web. Using Scott’s simple step-by-step method, with hundreds of ...

    Android异步消息处理机制实现原理详解

    消息处理机制主要对象:Looper,Handler,Message(还有...Looper.java static final ThreadLocal&lt;Looper&gt; sThreadLocal = new ThreadLocal(); private static Looper sMainLooper; // guarded by Looper.class final

Global site tag (gtag.js) - Google Analytics