1 7 8 package java.util.concurrent; 9 10 39 public enum TimeUnit { 40 NANOSECONDS(0), MICROSECONDS(1), MILLISECONDS(2), SECONDS(3); 41 42 43 private final int index; 44 45 46 TimeUnit(int index) { 47 this.index = index; 48 } 49 50 51 private static final int[] multipliers = { 52 1, 53 1000, 54 1000 * 1000, 55 1000 * 1000 * 1000 56 }; 57 58 63 private static final long[] overflows = { 64 0, Long.MAX_VALUE / 1000, 66 Long.MAX_VALUE / (1000 * 1000), 67 Long.MAX_VALUE / (1000 * 1000 * 1000) 68 }; 69 70 77 private static long doConvert(int delta, long duration) { 78 if (delta == 0) 79 return duration; 80 if (delta < 0) 81 return duration / multipliers[-delta]; 82 if (duration > overflows[delta]) 83 return Long.MAX_VALUE; 84 if (duration < -overflows[delta]) 85 return Long.MIN_VALUE; 86 return duration * multipliers[delta]; 87 } 88 89 105 public long convert(long duration, TimeUnit unit) { 106 return doConvert(unit.index - index, duration); 107 } 108 109 117 public long toNanos(long duration) { 118 return doConvert(index, duration); 119 } 120 121 129 public long toMicros(long duration) { 130 return doConvert(index - MICROSECONDS.index, duration); 131 } 132 133 141 public long toMillis(long duration) { 142 return doConvert(index - MILLISECONDS.index, duration); 143 } 144 145 151 public long toSeconds(long duration) { 152 return doConvert(index - SECONDS.index, duration); 153 } 154 155 156 160 private int excessNanos(long time, long ms) { 161 if (this == NANOSECONDS) 162 return (int) (time - (ms * 1000 * 1000)); 163 if (this == MICROSECONDS) 164 return (int) ((time * 1000) - (ms * 1000 * 1000)); 165 return 0; 166 } 167 168 189 public void timedWait(Object obj, long timeout) 190 throws InterruptedException { 191 if (timeout > 0) { 192 long ms = toMillis(timeout); 193 int ns = excessNanos(timeout, ms); 194 obj.wait(ms, ns); 195 } 196 } 197 198 207 public void timedJoin(Thread thread, long timeout) 208 throws InterruptedException { 209 if (timeout > 0) { 210 long ms = toMillis(timeout); 211 int ns = excessNanos(timeout, ms); 212 thread.join(ms, ns); 213 } 214 } 215 216 224 public void sleep(long timeout) throws InterruptedException { 225 if (timeout > 0) { 226 long ms = toMillis(timeout); 227 int ns = excessNanos(timeout, ms); 228 Thread.sleep(ms, ns); 229 } 230 } 231 232 } 233 | Popular Tags |