Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. public class Main {
  2. public static void main(String[] args) {
  3. Clerk clerk = new Clerk();
  4. new Thread(new Producer(clerk)).start();
  5. new Thread(new Consumer(clerk)).start();
  6. }
  7. }
  8.  
  9. class Clerk {
  10. private int product = 0;
  11.  
  12. public synchronized int getProduct() {
  13. if (this.product > 1) {
  14. System.err.println("產品超過1個, " + product);
  15. System.exit(0);
  16. }
  17. if (this.product < 1) {
  18. try {
  19. this.wait();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. this.product = this.product - 1;
  25. int product2 = this.product;
  26. this.notify();
  27. return product2;
  28. }
  29.  
  30. public synchronized int addProduct() {
  31. if (this.product > 1) {
  32. System.err.println("產品超過1個, " + product);
  33. System.exit(0);
  34. }
  35. if (this.product > 0) {
  36. try {
  37. this.wait();
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. this.product = this.product + 1;
  43. int product2 = this.product;
  44. this.notify();
  45. return product2;
  46. }
  47. }
  48.  
  49. class Producer implements Runnable {
  50. private Clerk clerk;
  51.  
  52. public Producer(Clerk clerk) {
  53. this.clerk = clerk;
  54. }
  55.  
  56. @Override
  57. public void run() {
  58. while (true) {
  59. int product = clerk.addProduct();
  60. System.out.println("生產者生產 1 個商品, 目前剩下的商品數量 " + product);
  61. }
  62. }
  63. }
  64.  
  65. class Consumer implements Runnable {
  66. private Clerk clerk;
  67.  
  68. public Consumer(Clerk clerk) {
  69. this.clerk = clerk;
  70. }
  71.  
  72. @Override
  73. public void run() {
  74. while (true) {
  75. int product = clerk.getProduct();
  76. System.out.println("消費者拿到 1 個商品, 目前剩下的商品數量 " + product);
  77. }
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement