java 6 多线程_JAVA多线程(六)模式-Balking

多线程共享一个资源,该资源发现无法提供服务则拒绝接受请求,请求将失败而不是继续等待资源。

适用环境对共享资源的请求是可被拒绝、不需要等待的。

样例秒杀。

只有一定数量的商品,超出数量的请求将被舍弃。

请求类

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 items=new LinkedList();

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()

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("秒杀结束!");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值