×
Traktatov.net » Философия Java » Читать онлайн
Страница 384 из 395 Настройки

//. concurrency/BankTel1erSimulation.java

// Пример использования очередей и многопоточного программирования. // {Args. 5}

import java.util.concurrent *. import java.util *;

// Объекты, доступные только для чтения, не требуют синхронизации-class Customer {

private final int serviceTime, public Customer(int tm) { serviceTime = tm; } public int getServiceTimeO { return serviceTime; } public String toStringO {

return "[" + serviceTime + "]";

}

}

// Очередь клиентов умеет выводить информацию о своем состоянии: class CustomerLine extends ArrayBlockingQueue { public Customerl_ine(int maxLineSize) { super(maxLineSize),

}

public String toStringO {

ifCthis sizeO == 0)

return "[Пусто]"; StringBuilder result = new StringBuilderO; for(Customer customer this)

result append(customer), return result toStringO,

}

}

// Случайное добавление клиентов в очередь: class CustomerGenerator implements Runnable { private CustomerLine customers, private static Random rand = new Random(47), public CustomerGenerator(CustomerLine cq) { customers = cq,

}

public void runO { try {

while(IThread.interruptedO) {

TimeUnit MILLISECONDS.sleep(rand nextlnt(300)):

продолжение &

customers put(new Customer(rand nextlnt(lOOO)));

}

} catchdnterruptedException e) {

System.out.pri ntin("CustomerGenerator i nterrupted");

}

System.out printin("CustomerGenerator terminating");

class Teller implements Runnable. Comparable { private static int counter = 0; private final int id = counter**; // Счетчик клиентов, обслуженных за текущую смену: private int customersServed = 0; private CustomerLine customers; private boolean servingCustomerLine = true; public Teller(CustomerLine cq) { customers = cq; } public void run О { try {

while(IThread.interruptedO) {

Customer customer = customers.takeO. Ti meUni t.MILLISECONDS.s1eep(

customer. getServiceTimeO); synchronized(this) {

customersServed++; while(IservingCustomerLine) waitO;

}

}

} catchdnterruptedException e) {

System out println(this + "прерван");

}

System out.println(this + "завершается");

}

public synchronized void doSomethingElseO { customersServed = 0; servingCustomerLine = false;

}

public synchronized void serveCustomerLineO {

assert IservingCustomerLine:"уже обслуживает: " + this; servingCustomerLine = true; notifyAl 10;

}

public String toStringO { return "Кассир " + id + " "; } public String shortStringO { return "K" + id. } // Используется приоритетной очередью: public synchronized int compareTo(Teller other) {

return customersServed < other customersServed ? -1 .

(customersServed == other.customersServed ? 0 . 1);

}

}

class TellerManager implements Runnable { private ExecutorService exec, private CustomerLine customers; private PriorityQueue workingTellers =

new PriorityQueue(); private Queue tellersDoingOtherThings =

new LinkedList(); private int adjustmentPeriod. private static Random rand = new Random(47); public TellerManager(ExecutorService e,

CustomerLine customers, int adjustmentPeriod) { exec = e;

this.customers = customers;

this.adjustmentPeriod = adjustmentPeriod;