好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java生产者消费者模式实例分析

本文实例讲述了java生产者消费者模式。分享给大家供大家参考,具体如下:

java的生产者消费者模式,有三个部分组成,一个是生产者,一个是消费者,一个是缓存。

这么做有什么好处呢?

1.解耦(去依赖),如果是消费者直接调用生产者,那如果生产者的代码变动了,消费者的代码也需要随之变动

2.高效,如果消费者直接掉生产者,执行时间较长的话,会阻塞,影响其他业务的进行

3.负载均衡,如果消费者直接调生产者,那生产者和消费者就得在一起了,日后业务量非常大的话,要想减轻服务器的压力,想拆分生产和消费,就很困难

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/**

  * 我是生产者,负责生产

  */

public class product implements runnable {

  private queue q;

  public product(queue q) {

  this .q = q;

  }

  @override

  public void run() {

  try {

   for ( int i = 0 ; i < 3 ; i++) {

   q.product( "test" + i);

   }

  } catch (interruptedexception e) {

   e.printstacktrace();

  }

  }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/**

  *我是消费者,负责消费

  */

public class consumer implements runnable {

  private queue q;

  public consumer(queue q){

  this .q = q;

  }

  @override

  public void run() {

  try {

   for ( int i= 0 ; i < 3 ; i++){

   q.consumer();

   }

  } catch (interruptedexception e) {

   e.printstacktrace();

  }

  }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

/**

  *

  *我是缓存,负责产品的存(生产后的放置)取(消费时的获取)

  */

public class queue {

  private final object lock = new object();

  private list<string> list = new arraylist<string>();

  public void product(string param) throws interruptedexception {

  synchronized (lock) {

   system.out.println( "product生产" );

   list.add(param);

   lock.notify();

   lock.wait();

  }

  }

  public void consumer() throws interruptedexception {

  synchronized (lock) {

   lock.wait();

   system.out.println( "product消费" );

   if (list.size() > 0 ) {

   list.remove(list.size() - 1 );

   }

   lock.notify();

  }

  }

}

public class testmain {

  public static void main(string[] args) {

  queue q = new queue();

  product p = new product(q);

  consumer s = new consumer(q);

  thread t1 = new thread(p);

  thread t2 = new thread(s);

  t1.start();

  t2.start();

  }

}

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/zy_281870667/article/details/70853474

查看更多关于Java生产者消费者模式实例分析的详细内容...

  阅读:19次