Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ServicePkg;
- public class Employee extends Thread {
- private static int employeeCounter = 0;
- private String employeeName;
- private Office myOffice;
- private boolean isWorking;
- public Employee(Office myOffice) {
- Employee.employeeCounter += 1;
- this.employeeName = "Employee #" + Employee.employeeCounter;
- this.myOffice = myOffice;
- isWorking = false;
- }
- public String getEmployeeName() {
- return this.employeeName;
- }
- public boolean isWorking() {
- return this.isWorking;
- }
- public void startWorking() {
- if (!isWorking) {
- isWorking = true;
- start();
- Utils.printLog("Working: " + employeeName + " start to work.");
- }
- }
- public synchronized void stopWorking() {
- isWorking = false;
- if (isWaiting()) {
- stopWaiting();
- }
- }
- public synchronized boolean isWaiting() {
- return getState() == Thread.State.WAITING;
- }
- public void stopWaiting() {
- if (isWaiting()) {
- synchronized (this) {
- notify();
- }
- }
- }
- @Override
- public void run() {
- while (isWorking) {
- Utils.printLog("Calling: " + this.employeeName
- + " is calling for customer.");
- Customer customer = this.myOffice.getNextCustomer();
- if (customer != null) {
- int serviceTime = Utils.getRandomServiceTime();
- Utils.printLog("Served : " + customer
- + " started to get service from " + this.employeeName
- + " for " + serviceTime + "ms");
- try {
- Thread.sleep(serviceTime);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Utils.printLog("EndSrv : " + customer + " has finished. "
- + this.employeeName + " is free.");
- } else if (myOffice.isOpen()) {
- // waiting for customers
- synchronized (this) {
- try {
- wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- } else {
- this.stopWorking();
- }
- }
- Utils.printLog("No Work: " + this.employeeName + " stop working.");
- }
- @Override
- public String toString() {
- return this.employeeName;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement