File tree Expand file tree Collapse file tree
concurrent/src/main/java/pcmodel Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package pcmodel ;
2+
3+ import java .util .List ;
4+
5+ /**
6+ * Created by 李恒名 on 2017/6/8.
7+ * <p>
8+ * 消费者
9+ */
10+ public class Consumer implements Runnable {
11+
12+ private List <Product > buffer ;
13+
14+ public Consumer (List <Product > buffer ) {
15+ this .buffer = buffer ;
16+ }
17+
18+ public void run () {
19+ while (true ) {
20+ synchronized (buffer ) {
21+ while (buffer .isEmpty ()) {
22+ try {
23+ buffer .wait ();
24+ } catch (InterruptedException e ) {
25+ e .printStackTrace ();
26+ }
27+ }
28+ System .out .println ("消费者[" + Thread .currentThread ().getName () + "]消费了一个产品:" + buffer .remove (0 ));
29+ buffer .notifyAll ();
30+ }
31+ }
32+ }
33+
34+
35+ }
Original file line number Diff line number Diff line change 1+ package pcmodel ;
2+
3+
4+ import java .util .List ;
5+
6+ /**
7+ * Created by 李恒名 on 2017/6/8.
8+ * <p>
9+ * 生产者
10+ */
11+ public class Producer implements Runnable {
12+
13+ private final int maxSize = 10 ;//产品最大库存量
14+
15+ private List <Product > buffer ;
16+
17+ public Producer (List <Product > buffer ) {
18+ this .buffer = buffer ;
19+ }
20+
21+ public void run () {
22+ while (true ) {
23+ synchronized (buffer ) {
24+ while (buffer .size () >= maxSize ) {
25+ try {
26+ buffer .wait ();//将当前线程放入等锁(buffer对象的锁)池,并释放锁。
27+ } catch (InterruptedException e ) {
28+ e .printStackTrace ();
29+ }
30+ }
31+ //模拟生产需要500毫秒
32+ try {
33+ Thread .sleep (500 );
34+ } catch (InterruptedException e ) {
35+ e .printStackTrace ();
36+ }
37+ Product product = new Product ("iPhone 手机" );
38+ buffer .add (product );
39+ System .out .println ("生产者[" + Thread .currentThread ().getName () + "]生产了一个产品:" + product );
40+ buffer .notifyAll ();//生产完毕通知等待锁的其他线程(生产者或消费者都有可能)
41+ }
42+ }
43+ }
44+ }
Original file line number Diff line number Diff line change 1+ package pcmodel ;
2+
3+ /**
4+ * Created by 李恒名 on 2017/6/8.
5+ *
6+ * 产品
7+ */
8+ public class Product {
9+
10+ private String name ;
11+
12+ public Product (String name ) {
13+ this .name = name ;
14+ }
15+
16+ @ Override
17+ public String toString () {
18+ return name ;
19+ }
20+ }
You can’t perform that action at this time.
0 commit comments