标签:java多线程 多线程模式 设计模式 模式 pattern
多线程共享一个资源,该资源发现无法提供服务则拒绝接受请求,请求将失败而不是继续等待资源。
对共享资源的请求是可被拒绝、不需要等待的。
秒杀。
只有一定数量的商品,超出数量的请求将被舍弃。
package Balking; public class Request { private String orderId=null; public Request(String orderId) { this.orderId=orderId; } public String getOrderId(){ return this.orderId; } }
package Balking; import java.util.LinkedList; //guarded object public class Inventory { private final LinkedList<Request> items=new LinkedList<Request>(); private final int size; public Inventory(int size){ this.size=size; } //guarded method public synchronized int put(Request req){ int ret=0; if(items.size()<size){ items.add(req); ret=1; } return ret; } public synchronized Request get(){ Request ret=null; ret=items.poll(); return ret; } }
package Balking; import java.util.UUID; public class Client implements Runnable{ private Inventory inventory=null; private final String myName; public Client(String myName,Inventory inventory){ this.inventory=inventory; this.myName=myName; } @Override public void run() { int ret=1; while(ret==1){ String orderId=UUID.randomUUID().toString(); Request req=new Request(orderId); ret=this.inventory.put(req); if(ret==1){ System.out.println(this.myName+" 订单:"+req.getOrderId()+"已提交!"); }else{ System.out.println(this.myName+" 商品已售罄!请求被拒绝!关闭请求渠道!"); } } } }
package Balking; public class Server implements Runnable{ private Inventory inventory=null; public Server(Inventory inventory){ this.inventory=inventory; } @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } int flag=0; while(flag==0){ Request req=this.inventory.get(); if(req!=null){ System.out.println("订单处理:"+req.getOrderId()); }else{ System.out.println("全部订单已处理完毕!"); flag=-1; } } } }
package Balking; public class Test { public static void main(String[] args) { Inventory inv=new Inventory(10); Client c1=new Client("c1",inv); Client c2=new Client("c2",inv); Client c3=new Client("c3",inv); Client c4=new Client("c4",inv); Client c5=new Client("c5",inv); Server s=new Server(inv); Thread ct1=new Thread(c1); Thread ct2=new Thread(c2); Thread ct3=new Thread(c3); Thread ct4=new Thread(c4); Thread ct5=new Thread(c5); Thread st=new Thread(s); ct1.start(); ct2.start(); ct3.start(); ct4.start(); ct5.start(); st.start(); try { ct1.join(); ct2.join(); ct3.join(); ct4.join(); ct5.join(); st.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("秒杀结束!"); } }
本文出自 “JAVA技术栈笔记” 博客,请务必保留此出处http://stroll.blog.51cto.com/11038467/1856629
标签:java多线程 多线程模式 设计模式 模式 pattern
原文地址:http://stroll.blog.51cto.com/11038467/1856629