Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. public class Main {
  2. public static void main(String[] args) {
  3. Bartender bartender = new Bartender();
  4. Thread bartenderThread = new Thread(bartender, "Bartender");
  5.  
  6. bartenderThread.start();
  7.  
  8. // Not very robust, but should allow the bartender to get to sleep first
  9. try {
  10. TimeUnit.SECONDS.sleep(1);
  11. } catch (InterruptedException e) {
  12. // This can be ignored
  13. }
  14.  
  15. int numCustomers = 1;
  16.  
  17. for (int i = 1; i <= numCustomers; i++) {
  18. String customerName = "Customer " + i;
  19. Customer customer = new Customer(bartenderThread, customerName, 10);
  20.  
  21. new Thread(customer, customerName).start();
  22. }
  23. }
  24.  
  25. public class Bartender implements Runnable {
  26. public void run() {
  27. System.out.println("Bartender: My boss isn't in today; time for a quick snooze!");
  28.  
  29. while (true) {
  30. if (Thread.interrupted()) { // Check to see if we have been interrupted,
  31. System.out.println("Bartender: I have to serve customer..");
  32. System.out.println("Serving customer...........");
  33. System.out.println("Serving customer DONE");
  34. }
  35.  
  36. try {
  37. TimeUnit.SECONDS.sleep(5);
  38. } catch (InterruptedException e) {
  39. System.out.println("Bartender Interrupted Exception Handler");
  40. Thread.currentThread().interrupt();
  41. }
  42. }
  43. }
  44.  
  45. public class Customer implements Runnable {
  46. private Thread bartenderThread;
  47. private String name;
  48. private int waitTime;
  49.  
  50. public Customer(Thread bartenderThread, String name, int waitTime) {
  51. this.bartenderThread = bartenderThread;
  52. this.name = name;
  53. this.waitTime = waitTime;
  54. }
  55.  
  56. public void run() {
  57. System.out.println(name + ": Doesn't seem to be anyone around. I'll wait a moment");
  58.  
  59. try {
  60. TimeUnit.SECONDS.sleep(waitTime);
  61. } catch (InterruptedException e) {
  62. // This can be ignored
  63. }
  64.  
  65. System.out.println(name + ": Oh there's a bell! Can I get some service around here?");
  66. System.out.println("bartenderThread: " + bartenderThread);
  67.  
  68. bartenderThread.interrupt(); //
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement