Biblioteca Java - Blame information for rev 29
Subversion Repositories:
Rev | Author | Line No. | Line |
---|---|---|---|
29 | mihai | 1 | package exemple.fire.consumerproducer; |
2 | |||
3 | import java.util.Random; | ||
4 | import java.util.concurrent.*; | ||
5 | |||
6 | class Producer implements Runnable { | ||
7 | private Random r = new Random(); | ||
8 | private final BlockingQueue queue; | ||
9 | |||
10 | Producer(BlockingQueue q) { queue = q; } | ||
11 | |||
12 | public void run() { | ||
13 | try { | ||
14 | while(true) { | ||
15 | Component com = produce(); | ||
16 | System.out.println("Add component:"+com); | ||
17 | queue.put(com); | ||
18 | } | ||
19 | } catch (InterruptedException ex) {ex.printStackTrace();} | ||
20 | } | ||
21 | |||
22 | Component produce() { | ||
23 | int y = r.nextInt(); | ||
24 | Component c = new Component(y); | ||
25 | return c; | ||
26 | } | ||
27 | } | ||
28 | |||
29 | class Consumer implements Runnable { | ||
30 | private final BlockingQueue queue; | ||
31 | Consumer(BlockingQueue q) { queue = q; } | ||
32 | public void run() { | ||
33 | try { | ||
34 | while(true) { consume(queue.take()); } | ||
35 | } catch (InterruptedException ex) {ex.printStackTrace();} | ||
36 | } | ||
37 | void consume(Object x) { | ||
38 | Component c = (Component)x; | ||
39 | c.process(); | ||
40 | System.out.println("Object "+x+" processed."); | ||
41 | |||
42 | } | ||
43 | } | ||
44 | |||
45 | public class Main { | ||
46 | public static void main(String[] args) { | ||
47 | BlockingQueue q = new ArrayBlockingQueue(4); | ||
48 | Producer p = new Producer(q); | ||
49 | Consumer c1 = new Consumer(q); | ||
50 | Consumer c2 = new Consumer(q); | ||
51 | new Thread(p).start(); | ||
52 | new Thread(c1).start(); | ||
53 | new Thread(c2).start(); | ||
54 | } | ||
55 | } | ||
56 | |||
57 | |||
58 | class Component{ | ||
59 | int type; | ||
60 | boolean processed = false; | ||
61 | |||
62 | Component(int type){this.type = type;} | ||
63 | |||
64 | void process(){ | ||
65 | //simulate some processind | ||
66 | try { | ||
67 | Thread.sleep(1000); | ||
68 | } catch (InterruptedException e) { | ||
69 | // TODO Auto-generated catch block | ||
70 | e.printStackTrace(); | ||
71 | } | ||
72 | processed =true; | ||
73 | } | ||
74 | |||
75 | @Override | ||
76 | public String toString() { | ||
77 | return "[type="+type+" processed="+processed+"]"; | ||
78 | } | ||
79 | } |