Java Implementation queueing theory

Source: Internet
Author: User
Tags static class

Reprint Please specify source: http://blog.csdn.net/xiaojimanman/article/details/50401727

Http://www.llwjy.com/blogdetail/3c3f556d2e98284111139e5690f078a1.html

Personal Blog Station has been online, the website www.llwjy.com ~ welcome you to vomit Groove ~

-------------------------------------------------------------------------------------------------

A few days ago to the bank to do business, the queue of people that is really many. Their formal business is less than 5 minutes, but the full wait for two hours (I believe very many people have encountered such a situation), the level of such service is really no language, but the problem has come. Banks should open a few forms, both to ensure the overall quality of service, but also to ensure the utilization of resources resources? Let's use the queuing theory to simulate this problem.


A brief introduction to queuing theory

Queuing theory is a mathematical theory and method for the study of system stochastic gathering and gathering phenomenon and stochastic system work project, also called Stochastic service system theory. As a branch of operations research.

The following is a simplified approach to queuing theory, first look at:

We have a number of blue desks on the left side of the graph, a red customer on the right, and a yellow waiting area in the middle, assuming the service desk is in the spare state. Customers can directly to accept the service, or in the yellow area to wait, customer service order from first to present service principle. Now that we know the probability distribution of the customer coming, then we can arrange a few desks on the left side to achieve better service level, but also guarantee the usage of the help desk? Here we build models to simulate this problem.


Implementation of queuing theory by step

1) for queuing theory, we first need to determine the customer attributes , know when the customer arrives, the need for service time, etc., we first create a customer class. Here we specify the maximum and minimum time for customer service, and here we directly feel that the service time is completely random in order to simplify:

public class Customerbean {//min service time private static int minservetime = 3 * 1000;//maximum service time private static int maxservetime = 15 * 1000;//customer reach time private long arrivetime;//customer need service time private int servetime;public Customerbean () {//Set arrival time Arrivetime = System.currenttimemillis ();//randomly Set customer service time servetime = (int) (Math.random () * (maxservetime-minservetime) + minservetime );}}

2) above we define the customer. Immediately after that, you need define a queued queue, let's first look at the properties of the queue, where we define an array. Use it to save queued customers, define the minimum, maximum time interval for the next customer arrival, and the probability that the customer will not come (here's a simple explanation, assuming the next customer's interval is 3.) However, the probability is calculated and satisfied, then the customer does not enter the queue, so the reason is to make the customer as far as possible to achieve a very large randomness, and the queue of the largest number of queues.

public class Customerquene {//Waiting for customer queue private linkedlist<customerbean> customers = new Linkedlist<customerbean > ();//The next customer comes in the shortest time private int mintime = 0;//Next customer comes up the maximum time private int maxtime = 1 * 1000;//to the probability of the customer private double rate = 0.9; Identify whether to continue to generate customer private Boolean flag = true;//max queue number private int maxwaitnum = 0;}

3) Both the customer and the queued queue are available, and we set up a thread that generates a customer, let it continue to produce customers. Here we have the time and probability distributions we have mentioned above.

/** * @Description: Generate customer Thread  * @Author: Lulei   * @Version: 1.1.0 */private class Customerthread extends Thread { Private Customerthread (String name) {super (name);} @Overridepublic void Run () {while (flag) {//Team end add a new customer if (Math.random () < rate) {Customers.addlast (New Customerbean ()) ; if (Maxwaitnum < Customers.size ()) {maxwaitnum = Customers.size ();}} int sleeptime = (int) (Math.random () * (maxtime-mintime) + mintime); try {TimeUnit.MILLISECONDS.sleep (sleeptime);} catch (Exception e) {E.printstacktrace ();}}}}

4) Assuming that there are customers in the queue who are queuing for spare, they need to get the team head of the customer to receive the service .

Public synchronized Customerbean Getcustomerbean () {if (customers = = NULL | | customers.size () < 1) {return null;} return Customers.removefirst ();}

5) Customer-related attributes and methods are ready. The following is a set of service-related properties, here we directly Service Desk Settingsinto threads and define some service metrics. such as the number of customer service, total waiting time, total service time, maximum waiting time, etc.

public class Servantthread extends thread{//service customer number private static int customernum = 0;//Total wait time private static int sumwaittime = 0;//Total service time private static int sumservetime = 0;//maximum wait time private static int maxwaittime = 0;private Boolean flag = FALSE;PR Ivate String name;}

6) The basic work of the service desk is Customer Service, here we write the service customer-related operations into the thread's Run method.

public void Run () {flag = True;while (flag) {Customerbean customer = Customerquene.getcustomerquene (). Getcustomerbean () ;//Assume that the customer thread is closed and there are no customers in the queue. The help desk thread closes the release if (customer = = null) {if (! Customerquene.getcustomerquene (). Isflag ()) {flag = False;print ();} Continue;} Long now = System.currenttimemillis (); int waitTime = (int) (Now-customer.getarrivetime ());//Save Maximum wait time if (WaitTime > m Axwaittime) {maxwaittime = WaitTime;} Sleep time is the service time of the customer. Represents this time in the service customer try {TimeUnit.MILLISECONDS.sleep (Customer.getservetime ());} catch (Exception e) {e.printstacktrace ();}  SYSTEM.ERR.PRINTLN (name + "Service Customer Time:" + customer.getservetime () + "Ms\t Customer wait:" + waitTime + "MS"); customernum++;sumwaittime + = Waittime;sumservetime + = Customer.getservetime ();}}

7) Finally we write a test modelTo verify the service level

/**   * @Description: */package      com.lulei.opsearch.quene;  Import Java.util.concurrent.TimeUnit;  public class Test {public static void main (string[] args) {//Open door System.out.println ("Pick up the door. "); Boolean flag = true; Customerquene.getcustomerquene (); Long a = System.currenttimemillis (); int servantnum = 10;for (int i = 0; i < Servantnum ; i++) {Servantthread thread = new Servantthread ("service desk" + i); Thread.Start ();} while (flag) {Long b = system.currenttimemillis (), if (b-a > 1 * * && flag) {//close flag = false; Customerquene.getcustomerquene (). Close (); System.out.println ("No Pick up!") ");} SYSTEM.OUT.PRINTLN ("System Execution Time:" + (B-A) + "MS"); SYSTEM.OUT.PRINTLN ("System spare Time:" + ((b-a) * Servantnum-servantthread.getsumservetime ())); Servantthread.print (); try {TimeUnit.SECONDS.sleep (2);} catch (Exception e) {e.printstacktrace ()}}}

Execution Results

1) Start of execution



2) customer generated thread shutdown



3) Final service level



By changing the number of service desks, you can evaluate how many desks should be set up in the current customer situation.


Full code

1) Customer Class

/** * @Description: */Package com.lulei.opsearch.quene;  public class Customerbean {//min service time private static int minservetime = 3 * 1000;//maximum service time private static int maxservetime = 15 * 1000;//customer reach time private long arrivetime;//customer need service time private int servetime;public Customerbean () {//Set arrival time Arrivetime = System.currenttimemillis ();//randomly Set customer service time servetime = (int) (Math.random () * (maxservetime-minservetime) + minservetime );} public static int Getminservetime () {return minservetime;} public static void Setminservetime (int minservetime) {customerbean.minservetime = Minservetime;} public static int Getmaxservetime () {return maxservetime;} public static void Setmaxservetime (int maxservetime) {customerbean.maxservetime = Maxservetime;} Public long Getarrivetime () {return arrivetime;} public void Setarrivetime (long arrivetime) {this.arrivetime = Arrivetime;} public int Getservetime () {return servetime;} public void setservetime (int servetime) {this.servetime = Servetime;}}


2) Customer Queue

 /** * @Description: */Package com.lulei.opsearch.quene;  Import Java.util.linkedlist;import Java.util.concurrent.TimeUnit; public class Customerquene {//Waiting for customer queue private linkedlist<customerbean> customers = new Linkedlist<customerbean > ();//The next customer comes in the shortest time private int mintime = 0;//Next customer comes up the maximum time private int maxtime = 1 * 1000;//to the probability of the customer private double rate = 0.9; Identify whether to continue to generate customer private Boolean flag = true;//Max queueing number private int maxwaitnum = 0;public int Getmaxwaitnum () {return maxwaitnum;} public Boolean Isflag () {return flag;} /** * @return * @Author: Lulei * @Description: Get the customer */public synchronized Customerbean Getcustomerbean () {if (custom ERS = = NULL | | Customers.size () < 1) {return null;} return Customers.removefirst ();} public void Close () {if (flag) {flag = false;}} /** * @return * @Author: Lulei * @Description: Get the number of waiting customers */public int getwaitcustomernum () {return customers.size ();} /** * @Description: Generate Customer Thread * @Author: Lulei * @Version: 1.1.0 */private class Customerthread Extends Thread {private customerthread (String name) {super (name);} @Overridepublic void Run () {while (flag) {//Team end add a new customer if (Math.random () < rate) {Customers.addlast (New Customerbean ()) ; if (Maxwaitnum < Customers.size ()) {maxwaitnum = Customers.size ();}} int sleeptime = (int) (Math.random () * (maxtime-mintime) + mintime); try {TimeUnit.MILLISECONDS.sleep (sleeptime);} catch (Exception e) {E.printstacktrace ();}}}} Singleton mode starts private static class Customerquenedao {private static Customerquene Customerquene = new Customerquene ();} Private Customerquene () {Customerthread customerthread = new Customerthread ("Customer generated thread"); Customerthread.start ();} public static Customerquene Getcustomerquene () {return customerquenedao.customerquene;} Singleton mode end public int getmintime () {return mintime;} public void setmintime (int mintime) {this.mintime = Mintime;} public int Getmaxtime () {return maxtime;} public void setmaxtime (int maxtime) {this.maxtime = MaxTime;} Public double getrate () {return rate;} public void Setrate (doubleRate) {this.rate = rate;}} 

3) service desk thread

 /** * @Description: */Package com.lulei.opsearch.quene;  Import Java.util.concurrent.timeunit;import Com.lulei.util.ParseUtil;  public class Servantthread extends thread{//service customer number private static int customernum = 0;//Total wait time private static int sumwaittime = 0;//Total service time private static int sumservetime = 0;//maximum wait time private static int maxwaittime = 0;private Boolean flag = FALSE;PR Ivate string Name;public servantthread (string name) {super (name); this.name = name;} public static int Getmaxwaittime () {return maxwaittime;} public static int Getsumservetime () {return sumservetime;} @Overridepublic void Run () {flag = True;while (flag) {Customerbean customer = Customerquene.getcustomerquene (). Getcustomerbean ();//Suppose the customer thread is closed and there are no customers in the queue. The help desk thread closes the release if (customer = = null) {if (! Customerquene.getcustomerquene (). Isflag ()) {flag = False;print ();} Continue;} Long now = System.currenttimemillis (); int waitTime = (int) (Now-customer.getarrivetime ());//Save Maximum wait time if (WaitTime > m Axwaittime) {maxwaittime = WaitTime;} //Sleep time for the customer's service time, which represents this time in the service customer try {TimeUnit.MILLISECONDS.sleep (Customer.getservetime ());} catch (Exception e) { E.printstacktrace ();}  SYSTEM.ERR.PRINTLN (name + "Service Customer Time:" + customer.getservetime () + "Ms\t Customer wait:" + waitTime + "MS"); customernum++;sumwaittime + = Waittime;sumservetime + = Customer.getservetime ();}} public static void print () {if (Customernum > 0) {System.out.println ("--------------------------------------"); System.out.println ("Number of customer service:" + customernum); System.out.println ("Max wait Time:" + maxwaittime); System.out.println ("Number of waiting Customers:" + customerquene.getcustomerquene (). Getwaitcustomernum ()); SYSTEM.OUT.PRINTLN ("Maximum number of waiting customers:" + customerquene.getcustomerquene (). Getmaxwaitnum ());//output customer average wait time. Keep two decimal System.out.println ("Average Customer wait Time:" + parseutil.parsedoubletodouble ((Sumwaittime * 1.0/customernum), 2) + "MS"); System.out.println ("Average customer service time:" + parseutil.parsedoubletodouble ((Sumservetime * 1.0/customernum), 2) + "MS"); SYSTEM.OUT.PRINTLN ("Total system service Time:" + sumservetime + "MS");}}}

4) test model

/**   * @Description: */package      com.lulei.opsearch.quene;  Import Java.util.concurrent.TimeUnit;  public class Test {public static void main (string[] args) {//Open door System.out.println ("Pick up the door!

"); Boolean flag = true; Customerquene.getcustomerquene (); Long a = System.currenttimemillis (); int servantnum = 10;for (int i = 0; i < Servantnum ; i++) {Servantthread thread = new Servantthread ("service desk" + i); Thread.Start ();} while (flag) {Long b = system.currenttimemillis (), if (b-a > 1 * * && flag) {//close flag = false; Customerquene.getcustomerquene (). Close (); System.out.println ("No Pick up!") ");} SYSTEM.OUT.PRINTLN ("System Execution Time:" + (B-A) + "MS"); SYSTEM.OUT.PRINTLN ("System spare Time:" + ((b-a) * Servantnum-servantthread.getsumservetime ())); Servantthread.print (); try {TimeUnit.SECONDS.sleep (2);} catch (Exception e) {e.printstacktrace ()}}}




-------------------------------------------------------------------------------------------------
Small welfare
-------------------------------------------------------------------------------------------------
The "Lucene Case development" course for individuals at the Geek College has been launched. Welcome everybody to spit the trough ~

First lesson: Lucene Overview

Lesson Two: Lucene often uses function introduction

Lesson Three: web crawler

Lesson Four: Database connection pooling

Lesson Five: Collection of novel sites

Lesson Six: novel Site database operations

The seventh lesson: the realization of the novel site distributed crawler

Java Implementation queueing theory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.