1 package cn.sice;
2
3 import java.util.ArrayList;
4 import java.util.Date;
5 import java.util.concurrent.locks.Condition;
6 import java.util.concurrent.locks.Lock;
7 import java.util.concurrent.locks.ReentrantLock;
8
9 public class LockDemo
10 {
11
12 public static void main(String[] args)
13 {
14 Res r = new Res();
15 In in = new In(r);
16 Out out = new Out(r);
17 new Thread(in).start();
18 new Thread(out).start();
19 }
20
21 }
22
23 class Res
24 {
25 ArrayList<String> arrList = new ArrayList();
26 Lock lock = new ReentrantLock();
27 Condition conSet = lock.newCondition();
28 Condition conGet = lock.newCondition();
29 boolean flag = false;
30
31 public void set()
32 {
33 lock.lock();
34 try
35 {
36 while (flag)
37 conSet.await();
38
39 arrList.add(new Date().toString());
40 System.out.println("SET----" + arrList.size() + "-- "
41 + arrList.get(arrList.size() - 1) + " *** "
42 + Thread.currentThread().getName());
43 flag = true;
44 conGet.signal();
45
46 } catch (InterruptedException e)
47 {
48 e.printStackTrace();
49 } finally
50 {
51 lock.unlock();
52 }
53
54 }
55
56 public void get()
57 {
58 lock.lock();
59 try
60 {
61 while (!flag)
62 conGet.await();
63 System.out.println("GET----" + arrList.size() + "-----"
64 + arrList.get(0) + " *** "
65 + Thread.currentThread().getName());
66 arrList.remove(0);
67 flag = false;
68 conSet.signal();
69 } catch (InterruptedException e)
70 {
71 e.printStackTrace();
72 } finally
73 {
74 lock.unlock();
75 }
76 }
77 }
78
79 class In implements Runnable
80 {
81 public void run()
82 {
83 while (true)
84 {
85 r.set();
86 }
87 }
88
89 private Res r;
90
91 public In(Res r)
92 {
93 this.r = r;
94 }
95 }
96
97 class Out implements Runnable
98 {
99 private Res r;
100
101 public Out(Res r)
102 {
103 this.r = r;
104 }
105
106 public void run()
107 {
108 while (true)
109 {
110 r.get();
111 }
112 }
113 }