码迷,mamicode.com
首页 > 编程语言 > 详细

java并发编程之Guarded Suspention

时间:2014-05-15 09:08:21      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:private   import   public   客户端   服务端   

当客户端请求速度远远大于服务端的处理速度,这时候就非常适合使用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

java并发编程之Guarded Suspention,布布扣,bubuko.com

java并发编程之Guarded Suspention

标签:private   import   public   客户端   服务端   

原文地址:http://fangchunliu.blog.51cto.com/1269779/1411302

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!