comparison dwtx/dwtxhelper/JThread.d @ 167:862b05e0334a

Add a wrapper for Thread
author Frank Benoit <benoit@tionex.de>
date Tue, 09 Sep 2008 15:59:16 +0200
parents
children 9e7e1a8bc813
comparison
equal deleted inserted replaced
163:e5dd0081ccba 167:862b05e0334a
1 module dwtx.dwtxhelper.JThread;
2
3 import tango.core.Thread;
4 import dwt.dwthelper.utils;
5
6 class JThread {
7
8 private Thread thread;
9 private Runnable runnable;
10
11 private alias ThreadLocal!(JThread) TTLS;
12 private static TTLS tls;
13
14 public static const int MAX_PRIORITY = 10;
15 public static const int MIN_PRIORITY = 1;
16 public static const int NORM_PRIORITY = 5;
17
18 private static TTLS getTls(){
19 if( tls is null ){
20 synchronized( JThread.classinfo ){
21 if( tls is null ){
22 tls = new TTLS();
23 }
24 }
25 }
26 return tls;
27 }
28
29 public this(){
30 thread = new Thread(&internalRun);
31 }
32 public this( void delegate() dg ){
33 thread = new Thread(&internalRun);
34 runnable = dgRunnable( dg );
35 }
36 public this(Runnable runnable){
37 thread = new Thread(&internalRun);
38 this.runnable = runnable;
39 }
40 public this(Runnable runnable, String name){
41 thread = new Thread(&internalRun);
42 this.runnable = runnable;
43 thread.name = name;
44 }
45 public this(String name){
46 thread = new Thread(&internalRun);
47 thread.name = name;
48 }
49
50 public void start(){
51 thread.start();
52 }
53
54 public static JThread currentThread(){
55 return getTls().val();
56 }
57 public int getPriority() {
58 return (thread.priority-Thread.PRIORITY_MIN) * (MAX_PRIORITY-MIN_PRIORITY) / (Thread.PRIORITY_MAX-Thread.PRIORITY_MIN) + MIN_PRIORITY;
59 }
60 public void setPriority( int newPriority ) {
61 thread.priority( (newPriority-MIN_PRIORITY) * (Thread.PRIORITY_MAX-Thread.PRIORITY_MIN) / (MAX_PRIORITY-MIN_PRIORITY) +Thread.PRIORITY_MIN );
62 }
63
64 private void internalRun(){
65 getTls().val( this );
66 if( runnable !is null ){
67 runnable.run();
68 }
69 else {
70 run();
71 }
72 }
73
74 public bool isAlive(){
75 return thread.isRunning();
76 }
77
78 public bool isDaemon() {
79 return thread.isDaemon();
80 }
81
82 public void join(){
83 thread.join();
84 }
85
86 public void setDaemon(bool on) {
87 thread.isDaemon(on);
88 }
89
90 public void setName(String name){
91 thread.name = name;
92 }
93 public String getName(){
94 return thread.name;
95 }
96
97 void interrupt() {
98 implMissing(__FILE__,__LINE__);
99 }
100
101 static bool interrupted() {
102 implMissing(__FILE__,__LINE__);
103 return false;
104 }
105
106 public void run(){
107 // default impl, do nothing
108 }
109 public static void sleep( int time ){
110 Thread.sleep(time/1000.0);
111 }
112 public Thread nativeThread(){
113 return thread;
114 }
115 public override char[] toString(){
116 return "JThread "~thread.name;
117 }
118 public static void yield(){
119 Thread.yield();
120 }
121 }
122