KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > demo > sharedqueue > Job


1 /*
2 @COPYRIGHT@
3 */

4 package demo.sharedqueue;
5
6 import java.util.Random JavaDoc;
7
8 public class Job {
9
10    private int duration;
11    private String JavaDoc producer;
12    private Worker consumer;
13    private int type;
14    private int state;
15    private String JavaDoc id;
16    private static final int STATE_READY = 0;
17    private static final int STATE_PROCESSING = 1;
18    private static final int STATE_COMPLETE = 2;
19    private static final int STATE_ABORTED = 3;
20
21    public Job(String JavaDoc producer, int id) {
22       Random JavaDoc random = new Random JavaDoc();
23       this.state = STATE_READY;
24       this.consumer = null;
25       this.producer = producer;
26       this.duration = random.nextInt(3) + 3;
27       this.type = random.nextInt(3) + 1;
28       this.id = Integer.toString(id);
29       while (this.id.length() < 3) {
30          this.id = "0" + this.id;
31       }
32    }
33
34    public void run(Worker consumer) {
35       synchronized (this) {
36          this.state = STATE_PROCESSING;
37          this.consumer = consumer;
38          try {
39             Thread.sleep(duration * 1000L);
40             this.state = STATE_COMPLETE;
41          }
42          catch (InterruptedException JavaDoc ie) {
43             this.state = STATE_ABORTED;
44          }
45       }
46    }
47
48    public String JavaDoc toXml() {
49       return "<job>" +
50             "<id>" + id + "</id>" +
51             "<type>" + type + "</type>" +
52             "<state>" + state + "</state>" +
53             "<producer>" + producer + "</producer>" +
54             "<consumer>" + getConsumer() + "</consumer>" +
55             "<duration>" + duration + "</duration>" +
56             "</job>";
57    }
58
59    private String JavaDoc getConsumer() {
60       return consumer == null ? "" : consumer.getName();
61    }
62 }
63
Popular Tags