首页 > 代码库 > java并发编程之Guarded Suspention
java并发编程之Guarded Suspention
当客户端请求速度远远大于服务端的处理速度,这时候就非常适合使用Guarded Suspention模式
package cn.fcl.guardendSuspension; import java.util.ArrayList; import java.util.List; public class RequestQueue { private List<Integer> integers = new ArrayList<Integer>(); public synchronized Integer get() { if(integers.size() == 0) { try { wait(); } catch (InterruptedException e) { } } return integers.remove(0); } public synchronized void add(Integer i) { integers.add(i); notify(); } } package cn.fcl.guardendSuspension; public class Client extends Thread { private RequestQueue queue; public Client(RequestQueue queue) { super(); this.queue = queue; } public void run() { for(int i = 0; i < 10; i++) { queue.add(i); } System.out.println("请求完毕"); } } package cn.fcl.guardendSuspension; public class Server extends Thread{ private RequestQueue queue; public Server(RequestQueue queue) { this.queue = queue; } @Override public void run() { while(true) { Integer i = queue.get(); System.out.println(i + "已经处理"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } package cn.fcl.guardendSuspension; public class main { public static void main(String[] args) { RequestQueue queue = new RequestQueue(); new Client(queue).start(); new Server(queue).start(); } }
本文出自 “温故而知新” 博客,请务必保留此出处http://fangchunliu.blog.51cto.com/1269779/1411302
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。