- balking
-
Multithreading shares a resource that discovers that a service is unavailable and rejects the request, and the request fails instead of continuing to wait for the Resource.
- Applicable environment
- Sample Example
- Request Class
-
-
Package Balking;public class Request {private string Orderid=null;public request (String OrderId) {this.orderid=orderid;} Public String Getorderid () {return this.orderid;}}
-
- Warehouse Class
-
-
Package Balking;import java.util.linkedlist;//guarded Objectpublic class Inventory {private final linkedlist< request> items=new linkedlist<request> ();p rivate final int size;public Inventory (int Size) {this.size=size;} Guarded methodpublic 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;}}
-
- Client
-
-
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;} @Overridepublic 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+ "order:" + Req.getorderid () + "submitted! ");} Else{system.out.println (this.myname+ "product is sold out! Request is denied! Close the request channel! ");}}}}
-
- Server-side
-
-
Package Balking;public class Server implements Runnable{private Inventory inventory=null;public Server (Inventory Inventory) {this.inventory=inventory;} @Overridepublic void Run () {try {thread.sleep ()} catch (interruptedexception e) {e.printstacktrace ();} int flag=0;while (flag==0) {Request req=this.inventory.get (); if (req!=null) {System.out.println ("order processing:" + Req.getorderid ());} Else{system.out.println ("all orders have been processed! "); flag=-1;}}}
-
- Test class
-
-
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 ("the second Kill is over!" ");}}
This article is from the Java technology stack notes blog, so be sure to keep this source http://stroll.blog.51cto.com/11038467/1856629
Java multithreading (vi) mode-balking