Biblioteca Java - Blame information for rev 29
Subversion Repositories:
Rev | Author | Line No. | Line |
---|---|---|---|
29 | mihai | 1 | package exemple.fire.synchronousqueue; |
2 | |||
3 | import java.util.Random; | ||
4 | import java.util.concurrent.SynchronousQueue; | ||
5 | |||
6 | public class SynchronousTest { | ||
7 | public static void main(String[] args) { | ||
8 | SynchronousQueue<String> q = new SynchronousQueue<String>(); | ||
9 | MessageGenerator mg = new MessageGenerator(q); | ||
10 | mg.start(); | ||
11 | |||
12 | MessageReader mr1 = new MessageReader(q); | ||
13 | mr1.start(); | ||
14 | } | ||
15 | } | ||
16 | |||
17 | class MessageGenerator extends Thread{ | ||
18 | SynchronousQueue<String> q; | ||
19 | boolean active = true; | ||
20 | public MessageGenerator(SynchronousQueue<String> q) { | ||
21 | this.q = q; | ||
22 | } | ||
23 | |||
24 | public void run(){ | ||
25 | Random r = new Random(); | ||
26 | while(active){ | ||
27 | int i = r.nextInt(); | ||
28 | System.out.println("Add new object."); | ||
29 | try { | ||
30 | q.put(" Generated int="+i); | ||
31 | } catch (InterruptedException e) { | ||
32 | // TODO Auto-generated catch block | ||
33 | e.printStackTrace(); | ||
34 | } | ||
35 | System.out.println("Object added."); | ||
36 | } | ||
37 | } | ||
38 | } | ||
39 | |||
40 | class MessageReader extends Thread{ | ||
41 | SynchronousQueue<String> q; | ||
42 | boolean active = true; | ||
43 | public MessageReader(SynchronousQueue<String> q) { | ||
44 | super(); | ||
45 | this.q = q; | ||
46 | } | ||
47 | public void run(){ | ||
48 | |||
49 | while(active){ | ||
50 | try { | ||
51 | String s = q.take(); | ||
52 | System.out.println("***Object received.Processing."); | ||
53 | int slp = (int)((Math.random()*10)); | ||
54 | |||
55 | Thread.sleep(slp*1000); | ||
56 | System.out.println("***Object processed."); | ||
57 | } catch (InterruptedException e) { | ||
58 | // TODO Auto-generated catch block | ||
59 | e.printStackTrace(); | ||
60 | } | ||
61 | } | ||
62 | } | ||
63 | } |