Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- tester.java
- =======================
- import java.util.Random;
- public class Tester {
- public static void main(String[] args) {
- Random rnd=new Random();
- final int TOTAL_VICTIMS=rnd.nextInt(50)+50;
- //create random number of customers
- Customer[] btlCust = new Customer[TOTAL_VICTIMS];
- for (int counter=0;counter<btlCust.length;counter+=1)
- {
- btlCust[counter]=new Customer();
- btlCust[counter].start();
- }
- System.out.println("Starting to serve");
- Pakid[] pkidim = new Pakid[5];
- for (int counter=0;counter<pkidim.length;counter+=1)
- {
- pkidim[counter]=new Pakid();
- pkidim[counter].start();
- }
- }
- }
- LocalBtl.java
- ===================
- public class LocalBtl {
- private static int nextInLine=0;
- public static int incLine()
- {
- nextInLine+=1;
- return nextInLine;
- }
- public static int getNextInLine()
- {
- return nextInLine;
- }
- }
- Pakid.java
- ==============
- import java.util.Random;
- public class Pakid extends Thread {
- private static int pakidNum=0;
- private int localPakidNum;
- boolean isOpen = true;
- Random rnd = new Random();
- public Pakid()
- {
- pakidNum+=1;
- localPakidNum=pakidNum;
- System.out.println("Pakid number #"+localPakidNum+" was created");
- }
- @Override
- public synchronized void run() {
- // TODO Auto-generated method stub
- while (isOpen) {
- while (LocalBtl.getNextInLine()<Customer.totalCustomers()) {
- System.out.println("Pakid #"+localPakidNum+" is Ready to serve");
- LocalBtl.incLine();
- long timeToServe = rnd.nextInt(500)+500;
- try {
- Thread.sleep(timeToServe);
- System.out.println("Customer#"+LocalBtl.getNextInLine()+" was served :"+timeToServe+"ms");
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- try {
- System.out.println("Pakid #"+localPakidNum+">Do not have any customer, me drinking some tea");
- Thread.sleep(5000);
- closeEmda();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("Pakid #"+localPakidNum+">i finished, have a nice day :)");
- }
- public void closeEmda() {
- this.isOpen = false;
- }
- }
- Customer.java
- =================
- public class Customer extends Thread {
- private static int getNumber=0;
- private int custNum;
- public Customer()
- {
- getNumber+=1;
- this.custNum=getNumber;
- System.out.println("Customer #"+custNum+" created.");
- }
- @Override
- public synchronized void run() {
- System.out.println("Customer #"+custNum+" is waiting");
- while (this.custNum>LocalBtl.getNextInLine())
- {
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("customer #"+this.custNum+" was served, thank you very clatch!");
- }
- public static int totalCustomers()
- {
- return getNumber;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment