Shredded a producer-consumer model

Producer - consumer model is a model often used in various fields of computer, how to achieve this simple model it?


problem analysis

  • First, you need a place to store producers to produce and consumers consume resources, simplicity we use an Object array as a resource pool to save resources.

  • Secondly, we know that there is a resource pool size limit, then when producers add resources to the resource pool must consider whether the resource pool filled. Similarly, when consumer spending resources must also consider the resource pool has no resources available for consumption, that is, the resource pool is empty. So how do we know that resource pool is full or empty it? Of course, is to add two properties to the resource pool to represent the state of the resource pool: notFull represents a non-full state, notEmpty represents a non-empty state.

  • Finally, the resource pool is a critical resource, producers and consumers can not be accessed (there are multiple producers and consumers. If the same access to resources can cause data errors). We need a lock to control access to the resource pool. ReentryLock used here for access control.
  • In summary, to achieve the most appropriate producer-consumer model but the use of ReentryLock with two conditions. The following is the implementation code.

Producer - consumer model code implementation

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
38
39
40
41
42
43
44
45
46
47
48
49
public  class < T > { Private Object [] Resources; large column   Shredded a producer-consumer model > Private int AddIndex, removeIndex, COUNT; Private Lock Lock = new new ReentryLock (); Private for condition Condition notFull lock.newCondition = (); Private for condition condition notEmpty lock.newCondition = (); public ( int size) { 		resources = new new Object [size]; 	} // Manufacturer production resources, if the resource pool is full, the producer enters a waiting state until there is space public void the addResource (T Resource) throws












InterruptedException {
Lock.lock (); the try { the while (Object.length COUNT ==) { notFull.await (); } Resources [AddIndex] = Resource; IF (++ AddIndex Object.length ==) { AddIndex = 0 ; } ++ COUNT; notEmpty.signal (); } a finally { lock.unlock (); } } // consumer spending resource, if the resource pool is empty, the consumer enters a waiting state until the resource pool resources are public T removeResource () { Lock.lock (); the try { the while (COUNT == 0 ) { notEmpty.await ();





















}
Object resource = resources[removeIndex];
if(++removeIndex==resources.length){
removeIndex==0;
}
--count;
notFull.signal();
return (T) resource;
}finally{
lock.unlock();
}
}
}

Guess you like

Origin www.cnblogs.com/liuzhongrong/p/12365271.html