在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java多线程综合练习——生产者消费者模式

2016-7-29 15:47| 发布者: zhangjf| 查看: 640| 评论: 0

摘要: 熟悉java多线程中休眠,synchronized,Thread.sleep(long)的用法 package cn.javase.mxy;class Product { private String kind; private String name; private String price; ...
熟悉java多线程中休眠,synchronized,Thread.sleep(long)的用法
  1. package cn.javase.mxy;
  2. class Product {
  3. private String kind;
  4. private String name;
  5. private String price;
  6. private boolean flag = true;
  7. public synchronized void set(String kind, String name, String price){
  8. if(this.flag == false){
  9. try {
  10. super.wait();
  11. } catch (InterruptedException e) {
  12. // TODO Auto-generated catch block
  13. e.printStackTrace();
  14. }
  15. }
  16. this.kind = kind;
  17. this.name = name;
  18. this.price = price;
  19. this.flag = false;
  20. super.notify();
  21. }
  22. public synchronized void get(){
  23. if(this.flag == true){
  24. try {
  25. super.wait();
  26. } catch (InterruptedException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. }
  30. }
  31. System.out.println("产品类型:"+kind+",产品名称:"+name+",产品价格:"+price);
  32. this.flag = true;
  33. super.notify();
  34. }
  35. }
  36. class Productor implements Runnable{
  37. private Product product;
  38. public Productor(Product product){
  39. this.product = product;
  40. }
  41. @Override
  42. public void run() {
  43. // TODO Auto-generated method stub
  44. for(int x = 0; x < 100; x++){
  45. try {
  46. Thread.sleep(100);
  47. } catch (InterruptedException e) {
  48. // TODO Auto-generated catch block
  49. e.printStackTrace();
  50. }
  51. if(x % 2 == 0){
  52. this.product.set("药品", "云南白药酊", "30元");
  53. }else{
  54. this.product.set("生活用品", "云南白药牙膏", "20元");
  55. }
  56. }
  57. }
  58. }
  59. class Consumer implements Runnable{
  60. private Product product;
  61. public Consumer (Product product){
  62. this.product = product;
  63. }
  64. @Override
  65. public void run() {
  66. // TODO Auto-generated method stub
  67. for(int x = 0; x < 100; x++){
  68. this.product.get();
  69. }
  70. }
  71. }
复制代码
  1. package cn.javase.mxy;
  2. public class Test {
  3. public static void main(String[] args) {
  4. Product p = new Product();
  5. new Thread(new Productor(p)).start();
  6. new Thread(new Consumer(p)).start();
  7. }
  8. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 12:21

Copyright 2015-2025 djqfx

返回顶部