[关闭]
@frank-shaw 2015-10-29T03:05:49.000000Z 字数 1335 阅读 2593

多生产者多消费者问题及代码

java.多线程


  1. package 生产者消费者;
  2. /*
  3. * 一开始想要做的是单生产者单消费者,没想到后来变成了多生产多消费,改一个东西就够了
  4. *
  5. * 经验教训:
  6. *
  7. * 1.notify()之前必须有另外一个线程正在wait(),否则notify()无效
  8. * 2.资源类不一定就需要实现接口Runnable,也可以作为实现接口类的输入量
  9. * 3.逻辑上需要能够过得去,不要写出来就依赖于调试,可以自己头脑运运
  10. */
  11. public class Producer1Customer1 {
  12. static Object lock = new Object();
  13. public static void main(String[] args) {
  14. Source ps = new Source();
  15. Producer p1 = new Producer(ps);
  16. Producer p2 = new Producer(ps);
  17. Producer p3 = new Producer(ps);
  18. Customer c1 = new Customer(ps);
  19. Customer c2 = new Customer(ps);
  20. Customer c3 = new Customer(ps);
  21. new Thread(p1).start();
  22. new Thread(p2).start();
  23. new Thread(p3).start();
  24. new Thread(c1).start();
  25. new Thread(c2).start();
  26. new Thread(c3).start();
  27. }
  28. }
  29. //资源类
  30. class Source{
  31. int num=100;
  32. boolean flag = false;
  33. }
  34. //生产者
  35. class Producer implements Runnable{
  36. Source ps;
  37. public Producer(Source ps){
  38. this.ps = ps;
  39. }
  40. @Override
  41. public void run() {
  42. while(true){
  43. synchronized(ps){
  44. if(ps.flag){
  45. if(ps.num >0){
  46. System.out.println(Thread.currentThread().getName()+"生产者"+ps.num);
  47. ps.num = ps.num -1;
  48. ps.flag = false;
  49. ps.notifyAll();
  50. }
  51. else return;
  52. }
  53. else{
  54. try{
  55. ps.wait();
  56. }catch(Exception e){
  57. e.printStackTrace();
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }
  64. //消费者
  65. class Customer implements Runnable{
  66. Source ps;
  67. public Customer(Source ps){
  68. this.ps = ps;
  69. }
  70. @Override
  71. public void run() {
  72. while(true){
  73. synchronized(ps){
  74. if(!ps.flag){
  75. if(ps.num>0){
  76. System.out.println(Thread.currentThread().getName()+"消费者" + ps.num);
  77. ps.flag = true;
  78. ps.notifyAll();
  79. }
  80. }
  81. else{
  82. try{
  83. ps.wait();
  84. }catch(Exception e){
  85. e.printStackTrace();
  86. }
  87. }
  88. }
  89. }
  90. }
  91. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注