KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > common > net > ObjectListeningThread


1 package org.lucane.common.net;
2
3 import java.util.*;
4
5 import org.lucane.common.Logging;
6
7 /**
8  * A thread that can listen on an ObjectConnection and notify listeners
9  */

10 class ObjectListeningThread extends Thread JavaDoc
11 {
12   //-- attributes
13
private ObjectConnection connection;
14   private ArrayList listeners;
15   private boolean end;
16
17   /**
18    * Constructor
19    *
20    * @param oc the ObjectConnection to listen
21    */

22   public ObjectListeningThread(ObjectConnection oc)
23   {
24     this.connection = oc;
25     this.listeners = new ArrayList();
26     this.end = false;
27   }
28
29   /**
30    * Add a listener
31    *
32    * @param ol the listener
33    */

34   public void addObjectListener(ObjectListener ol)
35   {
36     this.listeners.add(ol);
37   }
38
39   /**
40    * Stop the thread
41    */

42   public void close()
43   {
44     this.end = true;
45   }
46
47   /**
48    * Thread excecution
49    * Read messages and notify listeners
50    */

51   public void run()
52   {
53     while(!end)
54     {
55       if(this.connection.readyToRead())
56       {
57         try {
58           Object JavaDoc o = this.connection.read();
59           Iterator i = listeners.iterator();
60           while(i.hasNext())
61           {
62             ObjectListener ol = (ObjectListener)i.next();
63             ol.objectRead(o);
64           }
65         } catch(Exception JavaDoc e) {
66           Logging.getLogger().info(e.toString());
67         }
68       }
69       else
70       {
71         try {
72           Thread.sleep(50);
73         } catch(Exception JavaDoc e) {}
74       }
75     }
76   }
77 }
78
Popular Tags