1 9 package javolution.context; 10 11 import j2mex.realtime.MemoryArea; 12 import j2mex.realtime.RealtimeThread; 13 import javolution.lang.Reflection; 14 15 24 public class ConcurrentThread extends RealtimeThread implements 25 ConcurrentExecutor { 26 27 private volatile Runnable _logic; 28 29 private MemoryArea _memoryArea; 30 31 private int _priority; 32 33 private Status _status; 34 35 private boolean _terminate; 36 37 private String _name; 38 39 private Thread _source; 40 41 44 public ConcurrentThread() { 45 _name = "ConcurrentThread-" + getCount(); 46 if (SET_NAME != null) { 47 SET_NAME.invoke(this, _name); 48 } 49 if (SET_DAEMON != null) { 50 SET_DAEMON.invoke(this, new Boolean (true)); 51 } 52 } 53 54 private synchronized int getCount() { 55 return _Count++; 56 } 57 58 private static int _Count; 59 60 private static final Reflection.Method SET_NAME = Reflection 61 .getMethod("java.lang.Thread.setName(String)"); 62 63 private static final Reflection.Method SET_DAEMON = Reflection 64 .getMethod("java.lang.Thread.setDaemon(boolean)"); 65 66 69 public void run() { 70 while (true) { synchronized (this) { try { 73 while ((_logic == null) && !_terminate) 74 this.wait(); 75 } catch (InterruptedException e) { 76 throw new ConcurrentException(e); 77 } 78 } 79 if (_logic == null) 80 break; try { 82 Thread current = Thread.currentThread(); 83 if (current.getPriority() != _priority) { 84 current.setPriority(_priority); 85 } 86 _status.started(); 87 _memoryArea.executeInArea(_logic); 88 } catch (Throwable error) { 89 _status.error(error); 90 } finally { 91 _status.completed(); 92 _status = null; 93 _source = null; 94 _logic = null; } 96 } 97 } 98 99 public boolean execute(Runnable logic, Status status) { 101 if (_logic != null) 102 return false; synchronized (this) { 104 if (_logic != null) 105 return false; _memoryArea = RealtimeThread.getCurrentMemoryArea(); 107 _source = currentThread(); 108 if (_source instanceof ConcurrentThread) { 109 _source = ((ConcurrentThread) _source)._source; 110 } 111 _priority = _source.getPriority(); 112 _status = status; 113 _logic = logic; this.notify(); 115 return true; 116 } 117 } 118 119 public void terminate() { 121 synchronized (this) { 122 _terminate = true; 123 this.notify(); 124 } 125 } 126 127 133 public String toString() { 134 return _name + "(" + _source + ")"; 135 } 136 137 } 138 | Popular Tags |