Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Main {
- public static void main(String[] args) {
- Bartender bartender = new Bartender();
- Thread bartenderThread = new Thread(bartender, "Bartender");
- bartenderThread.start();
- // Not very robust, but should allow the bartender to get to sleep first
- try {
- TimeUnit.SECONDS.sleep(1);
- } catch (InterruptedException e) {
- // This can be ignored
- }
- int numCustomers = 1;
- for (int i = 1; i <= numCustomers; i++) {
- String customerName = "Customer " + i;
- Customer customer = new Customer(bartenderThread, customerName, 10);
- new Thread(customer, customerName).start();
- }
- }
- public class Bartender implements Runnable {
- public void run() {
- System.out.println("Bartender: My boss isn't in today; time for a quick snooze!");
- while (true) {
- if (Thread.interrupted()) { // Check to see if we have been interrupted,
- System.out.println("Bartender: I have to serve customer..");
- System.out.println("Serving customer...........");
- System.out.println("Serving customer DONE");
- }
- try {
- TimeUnit.SECONDS.sleep(5);
- } catch (InterruptedException e) {
- System.out.println("Bartender Interrupted Exception Handler");
- Thread.currentThread().interrupt();
- }
- }
- }
- public class Customer implements Runnable {
- private Thread bartenderThread;
- private String name;
- private int waitTime;
- public Customer(Thread bartenderThread, String name, int waitTime) {
- this.bartenderThread = bartenderThread;
- this.name = name;
- this.waitTime = waitTime;
- }
- public void run() {
- System.out.println(name + ": Doesn't seem to be anyone around. I'll wait a moment");
- try {
- TimeUnit.SECONDS.sleep(waitTime);
- } catch (InterruptedException e) {
- // This can be ignored
- }
- System.out.println(name + ": Oh there's a bell! Can I get some service around here?");
- System.out.println("bartenderThread: " + bartenderThread);
- bartenderThread.interrupt(); //
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement