OpenCores
URL https://opencores.org/ocsvn/scarts/scarts/trunk

Subversion Repositories scarts

[/] [scarts/] [trunk/] [toolchain/] [scarts-gcc/] [gcc-4.1.1/] [libjava/] [classpath/] [java/] [lang/] [Thread.java] - Blame information for rev 14

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 14 jlechner
/* Thread -- an independent thread of executable code
2
   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
3
   Free Software Foundation
4
 
5
This file is part of GNU Classpath.
6
 
7
GNU Classpath is free software; you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation; either version 2, or (at your option)
10
any later version.
11
 
12
GNU Classpath is distributed in the hope that it will be useful, but
13
WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
General Public License for more details.
16
 
17
You should have received a copy of the GNU General Public License
18
along with GNU Classpath; see the file COPYING.  If not, write to the
19
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20
02110-1301 USA.
21
 
22
Linking this library statically or dynamically with other modules is
23
making a combined work based on this library.  Thus, the terms and
24
conditions of the GNU General Public License cover the whole
25
combination.
26
 
27
As a special exception, the copyright holders of this library give you
28
permission to link this library with independent modules to produce an
29
executable, regardless of the license terms of these independent
30
modules, and to copy and distribute the resulting executable under
31
terms of your choice, provided that you also meet, for each linked
32
independent module, the terms and conditions of the license of that
33
module.  An independent module is a module which is not derived from
34
or based on this library.  If you modify this library, you may extend
35
this exception to your version of the library, but you are not
36
obligated to do so.  If you do not wish to do so, delete this
37
exception statement from your version. */
38
 
39
package java.lang;
40
 
41
import java.security.Permission;
42
import java.util.Map;
43
import java.util.WeakHashMap;
44
 
45
/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3
46
 * "The Java Language Specification", ISBN 0-201-63451-1
47
 * plus online API docs for JDK 1.2 beta from http://www.javasoft.com.
48
 * Status:  Believed complete to version 1.4, with caveats. We do not
49
 *          implement the deprecated (and dangerous) stop, suspend, and resume
50
 *          methods. Security implementation is not complete.
51
 */
52
 
53
/**
54
 * Thread represents a single thread of execution in the VM. When an
55
 * application VM starts up, it creates a non-daemon Thread which calls the
56
 * main() method of a particular class.  There may be other Threads running,
57
 * such as the garbage collection thread.
58
 *
59
 * <p>Threads have names to identify them.  These names are not necessarily
60
 * unique. Every Thread has a priority, as well, which tells the VM which
61
 * Threads should get more running time. New threads inherit the priority
62
 * and daemon status of the parent thread, by default.
63
 *
64
 * <p>There are two methods of creating a Thread: you may subclass Thread and
65
 * implement the <code>run()</code> method, at which point you may start the
66
 * Thread by calling its <code>start()</code> method, or you may implement
67
 * <code>Runnable</code> in the class you want to use and then call new
68
 * <code>Thread(your_obj).start()</code>.
69
 *
70
 * <p>The virtual machine runs until all non-daemon threads have died (either
71
 * by returning from the run() method as invoked by start(), or by throwing
72
 * an uncaught exception); or until <code>System.exit</code> is called with
73
 * adequate permissions.
74
 *
75
 * <p>It is unclear at what point a Thread should be added to a ThreadGroup,
76
 * and at what point it should be removed. Should it be inserted when it
77
 * starts, or when it is created?  Should it be removed when it is suspended
78
 * or interrupted?  The only thing that is clear is that the Thread should be
79
 * removed when it is stopped.
80
 *
81
 * @author Tom Tromey
82
 * @author John Keiser
83
 * @author Eric Blake (ebb9@email.byu.edu)
84
 * @see Runnable
85
 * @see Runtime#exit(int)
86
 * @see #run()
87
 * @see #start()
88
 * @see ThreadLocal
89
 * @since 1.0
90
 * @status updated to 1.4
91
 */
92
public class Thread implements Runnable
93
{
94
  /** The minimum priority for a Thread. */
95
  public static final int MIN_PRIORITY = 1;
96
 
97
  /** The priority a Thread gets by default. */
98
  public static final int NORM_PRIORITY = 5;
99
 
100
  /** The maximum priority for a Thread. */
101
  public static final int MAX_PRIORITY = 10;
102
 
103
  /** The underlying VM thread, only set when the thread is actually running.
104
   */
105
  volatile VMThread vmThread;
106
 
107
  /**
108
   * The group this thread belongs to. This is set to null by
109
   * ThreadGroup.removeThread when the thread dies.
110
   */
111
  volatile ThreadGroup group;
112
 
113
  /** The object to run(), null if this is the target. */
114
  final Runnable runnable;
115
 
116
  /** The thread name, non-null. */
117
  volatile String name;
118
 
119
  /** Whether the thread is a daemon. */
120
  volatile boolean daemon;
121
 
122
  /** The thread priority, 1 to 10. */
123
  volatile int priority;
124
 
125
  /** Native thread stack size. 0 = use default */
126
  private long stacksize;
127
 
128
  /** Was the thread stopped before it was started? */
129
  Throwable stillborn;
130
 
131
  /** The context classloader for this Thread. */
132
  private ClassLoader contextClassLoader;
133
 
134
  /** The next thread number to use. */
135
  private static int numAnonymousThreadsCreated;
136
 
137
  /** Thread local storage. Package accessible for use by
138
    * InheritableThreadLocal.
139
    */
140
  WeakHashMap locals;
141
 
142
  /**
143
   * Allocates a new <code>Thread</code> object. This constructor has
144
   * the same effect as <code>Thread(null, null,</code>
145
   * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
146
   * a newly generated name. Automatically generated names are of the
147
   * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
148
   * <p>
149
   * Threads created this way must have overridden their
150
   * <code>run()</code> method to actually do anything.  An example
151
   * illustrating this method being used follows:
152
   * <p><blockquote><pre>
153
   *     import java.lang.*;
154
   *
155
   *     class plain01 implements Runnable {
156
   *         String name;
157
   *         plain01() {
158
   *             name = null;
159
   *         }
160
   *         plain01(String s) {
161
   *             name = s;
162
   *         }
163
   *         public void run() {
164
   *             if (name == null)
165
   *                 System.out.println("A new thread created");
166
   *             else
167
   *                 System.out.println("A new thread with name " + name +
168
   *                                    " created");
169
   *         }
170
   *     }
171
   *     class threadtest01 {
172
   *         public static void main(String args[] ) {
173
   *             int failed = 0 ;
174
   *
175
   *             <b>Thread t1 = new Thread();</b>
176
   *             if (t1 != null)
177
   *                 System.out.println("new Thread() succeed");
178
   *             else {
179
   *                 System.out.println("new Thread() failed");
180
   *                 failed++;
181
   *             }
182
   *         }
183
   *     }
184
   * </pre></blockquote>
185
   *
186
   * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
187
   *          java.lang.Runnable, java.lang.String)
188
   */
189
  public Thread()
190
  {
191
    this(null, (Runnable) null);
192
  }
193
 
194
  /**
195
   * Allocates a new <code>Thread</code> object. This constructor has
196
   * the same effect as <code>Thread(null, target,</code>
197
   * <i>gname</i><code>)</code>, where <i>gname</i> is
198
   * a newly generated name. Automatically generated names are of the
199
   * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
200
   *
201
   * @param target the object whose <code>run</code> method is called.
202
   * @see java.lang.Thread#Thread(java.lang.ThreadGroup,
203
   *                              java.lang.Runnable, java.lang.String)
204
   */
205
  public Thread(Runnable target)
206
  {
207
    this(null, target);
208
  }
209
 
210
  /**
211
   * Allocates a new <code>Thread</code> object. This constructor has
212
   * the same effect as <code>Thread(null, null, name)</code>.
213
   *
214
   * @param   name   the name of the new thread.
215
   * @see     java.lang.Thread#Thread(java.lang.ThreadGroup,
216
   *          java.lang.Runnable, java.lang.String)
217
   */
218
  public Thread(String name)
219
  {
220
    this(null, null, name, 0);
221
  }
222
 
223
  /**
224
   * Allocates a new <code>Thread</code> object. This constructor has
225
   * the same effect as <code>Thread(group, target,</code>
226
   * <i>gname</i><code>)</code>, where <i>gname</i> is
227
   * a newly generated name. Automatically generated names are of the
228
   * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
229
   *
230
   * @param group the group to put the Thread into
231
   * @param target the Runnable object to execute
232
   * @throws SecurityException if this thread cannot access <code>group</code>
233
   * @throws IllegalThreadStateException if group is destroyed
234
   * @see #Thread(ThreadGroup, Runnable, String)
235
   */
236
  public Thread(ThreadGroup group, Runnable target)
237
  {
238
    this(group, target, "Thread-" + ++numAnonymousThreadsCreated, 0);
239
  }
240
 
241
  /**
242
   * Allocates a new <code>Thread</code> object. This constructor has
243
   * the same effect as <code>Thread(group, null, name)</code>
244
   *
245
   * @param group the group to put the Thread into
246
   * @param name the name for the Thread
247
   * @throws NullPointerException if name is null
248
   * @throws SecurityException if this thread cannot access <code>group</code>
249
   * @throws IllegalThreadStateException if group is destroyed
250
   * @see #Thread(ThreadGroup, Runnable, String)
251
   */
252
  public Thread(ThreadGroup group, String name)
253
  {
254
    this(group, null, name, 0);
255
  }
256
 
257
  /**
258
   * Allocates a new <code>Thread</code> object. This constructor has
259
   * the same effect as <code>Thread(null, target, name)</code>.
260
   *
261
   * @param target the Runnable object to execute
262
   * @param name the name for the Thread
263
   * @throws NullPointerException if name is null
264
   * @see #Thread(ThreadGroup, Runnable, String)
265
   */
266
  public Thread(Runnable target, String name)
267
  {
268
    this(null, target, name, 0);
269
  }
270
 
271
  /**
272
   * Allocate a new Thread object, with the specified ThreadGroup and name, and
273
   * using the specified Runnable object's <code>run()</code> method to
274
   * execute.  If the Runnable object is null, <code>this</code> (which is
275
   * a Runnable) is used instead.
276
   *
277
   * <p>If the ThreadGroup is null, the security manager is checked. If a
278
   * manager exists and returns a non-null object for
279
   * <code>getThreadGroup</code>, that group is used; otherwise the group
280
   * of the creating thread is used. Note that the security manager calls
281
   * <code>checkAccess</code> if the ThreadGroup is not null.
282
   *
283
   * <p>The new Thread will inherit its creator's priority and daemon status.
284
   * These can be changed with <code>setPriority</code> and
285
   * <code>setDaemon</code>.
286
   *
287
   * @param group the group to put the Thread into
288
   * @param target the Runnable object to execute
289
   * @param name the name for the Thread
290
   * @throws NullPointerException if name is null
291
   * @throws SecurityException if this thread cannot access <code>group</code>
292
   * @throws IllegalThreadStateException if group is destroyed
293
   * @see Runnable#run()
294
   * @see #run()
295
   * @see #setDaemon(boolean)
296
   * @see #setPriority(int)
297
   * @see SecurityManager#checkAccess(ThreadGroup)
298
   * @see ThreadGroup#checkAccess()
299
   */
300
  public Thread(ThreadGroup group, Runnable target, String name)
301
  {
302
    this(group, target, name, 0);
303
  }
304
 
305
  /**
306
   * Allocate a new Thread object, as if by
307
   * <code>Thread(group, null, name)</code>, and give it the specified stack
308
   * size, in bytes. The stack size is <b>highly platform independent</b>,
309
   * and the virtual machine is free to round up or down, or ignore it
310
   * completely.  A higher value might let you go longer before a
311
   * <code>StackOverflowError</code>, while a lower value might let you go
312
   * longer before an <code>OutOfMemoryError</code>.  Or, it may do absolutely
313
   * nothing! So be careful, and expect to need to tune this value if your
314
   * virtual machine even supports it.
315
   *
316
   * @param group the group to put the Thread into
317
   * @param target the Runnable object to execute
318
   * @param name the name for the Thread
319
   * @param size the stack size, in bytes; 0 to be ignored
320
   * @throws NullPointerException if name is null
321
   * @throws SecurityException if this thread cannot access <code>group</code>
322
   * @throws IllegalThreadStateException if group is destroyed
323
   * @since 1.4
324
   */
325
  public Thread(ThreadGroup group, Runnable target, String name, long size)
326
  {
327
    // Bypass System.getSecurityManager, for bootstrap efficiency.
328
    SecurityManager sm = SecurityManager.current;
329
    Thread current = currentThread();
330
    if (group == null)
331
      {
332
        if (sm != null)
333
            group = sm.getThreadGroup();
334
        if (group == null)
335
            group = current.group;
336
      }
337
    else if (sm != null)
338
        sm.checkAccess(group);
339
 
340
    this.group = group;
341
    // Use toString hack to detect null.
342
    this.name = name.toString();
343
    this.runnable = target;
344
    this.stacksize = size;
345
 
346
    priority = current.priority;
347
    daemon = current.daemon;
348
    contextClassLoader = current.contextClassLoader;
349
 
350
    group.addThread(this);
351
    InheritableThreadLocal.newChildThread(this);
352
  }
353
 
354
  /**
355
   * Used by the VM to create thread objects for threads started outside
356
   * of Java. Note: caller is responsible for adding the thread to
357
   * a group and InheritableThreadLocal.
358
   *
359
   * @param vmThread the native thread
360
   * @param name the thread name or null to use the default naming scheme
361
   * @param priority current priority
362
   * @param daemon is the thread a background thread?
363
   */
364
  Thread(VMThread vmThread, String name, int priority, boolean daemon)
365
  {
366
    this.vmThread = vmThread;
367
    this.runnable = null;
368
    if (name == null)
369
        name = "Thread-" + ++numAnonymousThreadsCreated;
370
    this.name = name;
371
    this.priority = priority;
372
    this.daemon = daemon;
373
    this.contextClassLoader = ClassLoader.getSystemClassLoader();
374
  }
375
 
376
  /**
377
   * Get the number of active threads in the current Thread's ThreadGroup.
378
   * This implementation calls
379
   * <code>currentThread().getThreadGroup().activeCount()</code>.
380
   *
381
   * @return the number of active threads in the current ThreadGroup
382
   * @see ThreadGroup#activeCount()
383
   */
384
  public static int activeCount()
385
  {
386
    return currentThread().group.activeCount();
387
  }
388
 
389
  /**
390
   * Check whether the current Thread is allowed to modify this Thread. This
391
   * passes the check on to <code>SecurityManager.checkAccess(this)</code>.
392
   *
393
   * @throws SecurityException if the current Thread cannot modify this Thread
394
   * @see SecurityManager#checkAccess(Thread)
395
   */
396
  public final void checkAccess()
397
  {
398
    // Bypass System.getSecurityManager, for bootstrap efficiency.
399
    SecurityManager sm = SecurityManager.current;
400
    if (sm != null)
401
      sm.checkAccess(this);
402
  }
403
 
404
  /**
405
   * Count the number of stack frames in this Thread.  The Thread in question
406
   * must be suspended when this occurs.
407
   *
408
   * @return the number of stack frames in this Thread
409
   * @throws IllegalThreadStateException if this Thread is not suspended
410
   * @deprecated pointless, since suspend is deprecated
411
   */
412
  public int countStackFrames()
413
  {
414
    VMThread t = vmThread;
415
    if (t == null || group == null)
416
        throw new IllegalThreadStateException();
417
 
418
    return t.countStackFrames();
419
  }
420
 
421
  /**
422
   * Get the currently executing Thread. In the situation that the
423
   * currently running thread was created by native code and doesn't
424
   * have an associated Thread object yet, a new Thread object is
425
   * constructed and associated with the native thread.
426
   *
427
   * @return the currently executing Thread
428
   */
429
  public static Thread currentThread()
430
  {
431
    return VMThread.currentThread();
432
  }
433
 
434
  /**
435
   * Originally intended to destroy this thread, this method was never
436
   * implemented by Sun, and is hence a no-op.
437
   */
438
  public void destroy()
439
  {
440
    throw new NoSuchMethodError();
441
  }
442
 
443
  /**
444
   * Print a stack trace of the current thread to stderr using the same
445
   * format as Throwable's printStackTrace() method.
446
   *
447
   * @see Throwable#printStackTrace()
448
   */
449
  public static void dumpStack()
450
  {
451
    new Throwable().printStackTrace();
452
  }
453
 
454
  /**
455
   * Copy every active thread in the current Thread's ThreadGroup into the
456
   * array. Extra threads are silently ignored. This implementation calls
457
   * <code>getThreadGroup().enumerate(array)</code>, which may have a
458
   * security check, <code>checkAccess(group)</code>.
459
   *
460
   * @param array the array to place the Threads into
461
   * @return the number of Threads placed into the array
462
   * @throws NullPointerException if array is null
463
   * @throws SecurityException if you cannot access the ThreadGroup
464
   * @see ThreadGroup#enumerate(Thread[])
465
   * @see #activeCount()
466
   * @see SecurityManager#checkAccess(ThreadGroup)
467
   */
468
  public static int enumerate(Thread[] array)
469
  {
470
    return currentThread().group.enumerate(array);
471
  }
472
 
473
  /**
474
   * Get this Thread's name.
475
   *
476
   * @return this Thread's name
477
   */
478
  public final String getName()
479
  {
480
    VMThread t = vmThread;
481
    return t == null ? name : t.getName();
482
  }
483
 
484
  /**
485
   * Get this Thread's priority.
486
   *
487
   * @return the Thread's priority
488
   */
489
  public final synchronized int getPriority()
490
  {
491
    VMThread t = vmThread;
492
    return t == null ? priority : t.getPriority();
493
  }
494
 
495
  /**
496
   * Get the ThreadGroup this Thread belongs to. If the thread has died, this
497
   * returns null.
498
   *
499
   * @return this Thread's ThreadGroup
500
   */
501
  public final ThreadGroup getThreadGroup()
502
  {
503
    return group;
504
  }
505
 
506
  /**
507
   * Checks whether the current thread holds the monitor on a given object.
508
   * This allows you to do <code>assert Thread.holdsLock(obj)</code>.
509
   *
510
   * @param obj the object to test lock ownership on.
511
   * @return true if the current thread is currently synchronized on obj
512
   * @throws NullPointerException if obj is null
513
   * @since 1.4
514
   */
515
  public static boolean holdsLock(Object obj)
516
  {
517
    return VMThread.holdsLock(obj);
518
  }
519
 
520
  /**
521
   * Interrupt this Thread. First, there is a security check,
522
   * <code>checkAccess</code>. Then, depending on the current state of the
523
   * thread, various actions take place:
524
   *
525
   * <p>If the thread is waiting because of {@link #wait()},
526
   * {@link #sleep(long)}, or {@link #join()}, its <i>interrupt status</i>
527
   * will be cleared, and an InterruptedException will be thrown. Notice that
528
   * this case is only possible if an external thread called interrupt().
529
   *
530
   * <p>If the thread is blocked in an interruptible I/O operation, in
531
   * {@link java.nio.channels.InterruptibleChannel}, the <i>interrupt
532
   * status</i> will be set, and ClosedByInterruptException will be thrown.
533
   *
534
   * <p>If the thread is blocked on a {@link java.nio.channels.Selector}, the
535
   * <i>interrupt status</i> will be set, and the selection will return, with
536
   * a possible non-zero value, as though by the wakeup() method.
537
   *
538
   * <p>Otherwise, the interrupt status will be set.
539
   *
540
   * @throws SecurityException if you cannot modify this Thread
541
   */
542
  public synchronized void interrupt()
543
  {
544
    checkAccess();
545
    VMThread t = vmThread;
546
    if (t != null)
547
        t.interrupt();
548
  }
549
 
550
  /**
551
   * Determine whether the current Thread has been interrupted, and clear
552
   * the <i>interrupted status</i> in the process.
553
   *
554
   * @return whether the current Thread has been interrupted
555
   * @see #isInterrupted()
556
   */
557
  public static boolean interrupted()
558
  {
559
    return VMThread.interrupted();
560
  }
561
 
562
  /**
563
   * Determine whether the given Thread has been interrupted, but leave
564
   * the <i>interrupted status</i> alone in the process.
565
   *
566
   * @return whether the Thread has been interrupted
567
   * @see #interrupted()
568
   */
569
  public boolean isInterrupted()
570
  {
571
    VMThread t = vmThread;
572
    return t != null && t.isInterrupted();
573
  }
574
 
575
  /**
576
   * Determine whether this Thread is alive. A thread which is alive has
577
   * started and not yet died.
578
   *
579
   * @return whether this Thread is alive
580
   */
581
  public final boolean isAlive()
582
  {
583
    return vmThread != null && group != null;
584
  }
585
 
586
  /**
587
   * Tell whether this is a daemon Thread or not.
588
   *
589
   * @return whether this is a daemon Thread or not
590
   * @see #setDaemon(boolean)
591
   */
592
  public final boolean isDaemon()
593
  {
594
    VMThread t = vmThread;
595
    return t == null ? daemon : t.isDaemon();
596
  }
597
 
598
  /**
599
   * Wait forever for the Thread in question to die.
600
   *
601
   * @throws InterruptedException if the Thread is interrupted; it's
602
   *         <i>interrupted status</i> will be cleared
603
   */
604
  public final void join() throws InterruptedException
605
  {
606
    join(0, 0);
607
  }
608
 
609
  /**
610
   * Wait the specified amount of time for the Thread in question to die.
611
   *
612
   * @param ms the number of milliseconds to wait, or 0 for forever
613
   * @throws InterruptedException if the Thread is interrupted; it's
614
   *         <i>interrupted status</i> will be cleared
615
   */
616
  public final void join(long ms) throws InterruptedException
617
  {
618
    join(ms, 0);
619
  }
620
 
621
  /**
622
   * Wait the specified amount of time for the Thread in question to die.
623
   *
624
   * <p>Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs do
625
   * not offer that fine a grain of timing resolution. Besides, there is
626
   * no guarantee that this thread can start up immediately when time expires,
627
   * because some other thread may be active.  So don't expect real-time
628
   * performance.
629
   *
630
   * @param ms the number of milliseconds to wait, or 0 for forever
631
   * @param ns the number of extra nanoseconds to sleep (0-999999)
632
   * @throws InterruptedException if the Thread is interrupted; it's
633
   *         <i>interrupted status</i> will be cleared
634
   * @throws IllegalArgumentException if ns is invalid
635
   */
636
  public final void join(long ms, int ns) throws InterruptedException
637
  {
638
    if(ms < 0 || ns < 0 || ns > 999999)
639
        throw new IllegalArgumentException();
640
 
641
    VMThread t = vmThread;
642
    if(t != null)
643
        t.join(ms, ns);
644
  }
645
 
646
  /**
647
   * Resume this Thread.  If the thread is not suspended, this method does
648
   * nothing. To mirror suspend(), there may be a security check:
649
   * <code>checkAccess</code>.
650
   *
651
   * @throws SecurityException if you cannot resume the Thread
652
   * @see #checkAccess()
653
   * @see #suspend()
654
   * @deprecated pointless, since suspend is deprecated
655
   */
656
  public final synchronized void resume()
657
  {
658
    checkAccess();
659
    VMThread t = vmThread;
660
    if (t != null)
661
        t.resume();
662
  }
663
 
664
  /**
665
   * The method of Thread that will be run if there is no Runnable object
666
   * associated with the Thread. Thread's implementation does nothing at all.
667
   *
668
   * @see #start()
669
   * @see #Thread(ThreadGroup, Runnable, String)
670
   */
671
  public void run()
672
  {
673
    if (runnable != null)
674
      runnable.run();
675
  }
676
 
677
  /**
678
   * Set the daemon status of this Thread.  If this is a daemon Thread, then
679
   * the VM may exit even if it is still running.  This may only be called
680
   * before the Thread starts running. There may be a security check,
681
   * <code>checkAccess</code>.
682
   *
683
   * @param daemon whether this should be a daemon thread or not
684
   * @throws SecurityException if you cannot modify this Thread
685
   * @throws IllegalThreadStateException if the Thread is active
686
   * @see #isDaemon()
687
   * @see #checkAccess()
688
   */
689
  public final synchronized void setDaemon(boolean daemon)
690
  {
691
    if (vmThread != null)
692
      throw new IllegalThreadStateException();
693
    checkAccess();
694
    this.daemon = daemon;
695
  }
696
 
697
  /**
698
   * Returns the context classloader of this Thread. The context
699
   * classloader can be used by code that want to load classes depending
700
   * on the current thread. Normally classes are loaded depending on
701
   * the classloader of the current class. There may be a security check
702
   * for <code>RuntimePermission("getClassLoader")</code> if the caller's
703
   * class loader is not null or an ancestor of this thread's context class
704
   * loader.
705
   *
706
   * @return the context class loader
707
   * @throws SecurityException when permission is denied
708
   * @see #setContextClassLoader(ClassLoader)
709
   * @since 1.2
710
   */
711
  public synchronized ClassLoader getContextClassLoader()
712
  {
713
    // Bypass System.getSecurityManager, for bootstrap efficiency.
714
    SecurityManager sm = SecurityManager.current;
715
    if (sm != null)
716
      // XXX Don't check this if the caller's class loader is an ancestor.
717
      sm.checkPermission(new RuntimePermission("getClassLoader"));
718
    return contextClassLoader;
719
  }
720
 
721
  /**
722
   * Sets the context classloader for this Thread. When not explicitly set,
723
   * the context classloader for a thread is the same as the context
724
   * classloader of the thread that created this thread. The first thread has
725
   * as context classloader the system classloader. There may be a security
726
   * check for <code>RuntimePermission("setContextClassLoader")</code>.
727
   *
728
   * @param classloader the new context class loader
729
   * @throws SecurityException when permission is denied
730
   * @see #getContextClassLoader()
731
   * @since 1.2
732
   */
733
  public synchronized void setContextClassLoader(ClassLoader classloader)
734
  {
735
    SecurityManager sm = SecurityManager.current;
736
    if (sm != null)
737
      sm.checkPermission(new RuntimePermission("setContextClassLoader"));
738
    this.contextClassLoader = classloader;
739
  }
740
 
741
  /**
742
   * Set this Thread's name.  There may be a security check,
743
   * <code>checkAccess</code>.
744
   *
745
   * @param name the new name for this Thread
746
   * @throws NullPointerException if name is null
747
   * @throws SecurityException if you cannot modify this Thread
748
   */
749
  public final synchronized void setName(String name)
750
  {
751
    checkAccess();
752
    // The Class Libraries book says ``threadName cannot be null''.  I
753
    // take this to mean NullPointerException.
754
    if (name == null)
755
      throw new NullPointerException();
756
    VMThread t = vmThread;
757
    if (t != null)
758
        t.setName(name);
759
    else
760
        this.name = name;
761
  }
762
 
763
  /**
764
   * Yield to another thread. The Thread will not lose any locks it holds
765
   * during this time. There are no guarantees which thread will be
766
   * next to run, and it could even be this one, but most VMs will choose
767
   * the highest priority thread that has been waiting longest.
768
   */
769
  public static void yield()
770
  {
771
    VMThread.yield();
772
  }
773
 
774
  /**
775
   * Suspend the current Thread's execution for the specified amount of
776
   * time. The Thread will not lose any locks it has during this time. There
777
   * are no guarantees which thread will be next to run, but most VMs will
778
   * choose the highest priority thread that has been waiting longest.
779
   *
780
   * @param ms the number of milliseconds to sleep.
781
   * @throws InterruptedException if the Thread is (or was) interrupted;
782
   *         it's <i>interrupted status</i> will be cleared
783
   * @throws IllegalArgumentException if ms is negative
784
   * @see #interrupt()
785
   */
786
  public static void sleep(long ms) throws InterruptedException
787
  {
788
    sleep(ms, 0);
789
  }
790
 
791
  /**
792
   * Suspend the current Thread's execution for the specified amount of
793
   * time. The Thread will not lose any locks it has during this time. There
794
   * are no guarantees which thread will be next to run, but most VMs will
795
   * choose the highest priority thread that has been waiting longest.
796
   * <p>
797
   * Note that 1,000,000 nanoseconds == 1 millisecond, but most VMs
798
   * do not offer that fine a grain of timing resolution. When ms is
799
   * zero and ns is non-zero the Thread will sleep for at least one
800
   * milli second. There is no guarantee that this thread can start up
801
   * immediately when time expires, because some other thread may be
802
   * active.  So don't expect real-time performance.
803
   *
804
   * @param ms the number of milliseconds to sleep
805
   * @param ns the number of extra nanoseconds to sleep (0-999999)
806
   * @throws InterruptedException if the Thread is (or was) interrupted;
807
   *         it's <i>interrupted status</i> will be cleared
808
   * @throws IllegalArgumentException if ms or ns is negative
809
   *         or ns is larger than 999999.
810
   * @see #interrupt()
811
   */
812
  public static void sleep(long ms, int ns) throws InterruptedException
813
  {
814
 
815
    // Check parameters
816
    if (ms < 0 )
817
      throw new IllegalArgumentException("Negative milliseconds: " + ms);
818
 
819
    if (ns < 0 || ns > 999999)
820
      throw new IllegalArgumentException("Nanoseconds ouf of range: " + ns);
821
 
822
    // Really sleep
823
    VMThread.sleep(ms, ns);
824
  }
825
 
826
  /**
827
   * Start this Thread, calling the run() method of the Runnable this Thread
828
   * was created with, or else the run() method of the Thread itself. This
829
   * is the only way to start a new thread; calling run by yourself will just
830
   * stay in the same thread. The virtual machine will remove the thread from
831
   * its thread group when the run() method completes.
832
   *
833
   * @throws IllegalThreadStateException if the thread has already started
834
   * @see #run()
835
   */
836
  public synchronized void start()
837
  {
838
    if (vmThread != null || group == null)
839
        throw new IllegalThreadStateException();
840
 
841
    VMThread.create(this, stacksize);
842
  }
843
 
844
  /**
845
   * Cause this Thread to stop abnormally because of the throw of a ThreadDeath
846
   * error. If you stop a Thread that has not yet started, it will stop
847
   * immediately when it is actually started.
848
   *
849
   * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
850
   * leave data in bad states.  Hence, there is a security check:
851
   * <code>checkAccess(this)</code>, plus another one if the current thread
852
   * is not this: <code>RuntimePermission("stopThread")</code>. If you must
853
   * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
854
   * ThreadDeath is the only exception which does not print a stack trace when
855
   * the thread dies.
856
   *
857
   * @throws SecurityException if you cannot stop the Thread
858
   * @see #interrupt()
859
   * @see #checkAccess()
860
   * @see #start()
861
   * @see ThreadDeath
862
   * @see ThreadGroup#uncaughtException(Thread, Throwable)
863
   * @see SecurityManager#checkAccess(Thread)
864
   * @see SecurityManager#checkPermission(Permission)
865
   * @deprecated unsafe operation, try not to use
866
   */
867
  public final void stop()
868
  {
869
    stop(new ThreadDeath());
870
  }
871
 
872
  /**
873
   * Cause this Thread to stop abnormally and throw the specified exception.
874
   * If you stop a Thread that has not yet started, the stop is ignored
875
   * (contrary to what the JDK documentation says).
876
   * <b>WARNING</b>This bypasses Java security, and can throw a checked
877
   * exception which the call stack is unprepared to handle. Do not abuse
878
   * this power.
879
   *
880
   * <p>This is inherently unsafe, as it can interrupt synchronized blocks and
881
   * leave data in bad states.  Hence, there is a security check:
882
   * <code>checkAccess(this)</code>, plus another one if the current thread
883
   * is not this: <code>RuntimePermission("stopThread")</code>. If you must
884
   * catch a ThreadDeath, be sure to rethrow it after you have cleaned up.
885
   * ThreadDeath is the only exception which does not print a stack trace when
886
   * the thread dies.
887
   *
888
   * @param t the Throwable to throw when the Thread dies
889
   * @throws SecurityException if you cannot stop the Thread
890
   * @throws NullPointerException in the calling thread, if t is null
891
   * @see #interrupt()
892
   * @see #checkAccess()
893
   * @see #start()
894
   * @see ThreadDeath
895
   * @see ThreadGroup#uncaughtException(Thread, Throwable)
896
   * @see SecurityManager#checkAccess(Thread)
897
   * @see SecurityManager#checkPermission(Permission)
898
   * @deprecated unsafe operation, try not to use
899
   */
900
  public final synchronized void stop(Throwable t)
901
  {
902
    if (t == null)
903
      throw new NullPointerException();
904
    // Bypass System.getSecurityManager, for bootstrap efficiency.
905
    SecurityManager sm = SecurityManager.current;
906
    if (sm != null)
907
      {
908
        sm.checkAccess(this);
909
        if (this != currentThread())
910
          sm.checkPermission(new RuntimePermission("stopThread"));
911
      }
912
    VMThread vt = vmThread;
913
    if (vt != null)
914
        vt.stop(t);
915
    else
916
        stillborn = t;
917
  }
918
 
919
  /**
920
   * Suspend this Thread.  It will not come back, ever, unless it is resumed.
921
   *
922
   * <p>This is inherently unsafe, as the suspended thread still holds locks,
923
   * and can potentially deadlock your program.  Hence, there is a security
924
   * check: <code>checkAccess</code>.
925
   *
926
   * @throws SecurityException if you cannot suspend the Thread
927
   * @see #checkAccess()
928
   * @see #resume()
929
   * @deprecated unsafe operation, try not to use
930
   */
931
  public final synchronized void suspend()
932
  {
933
    checkAccess();
934
    VMThread t = vmThread;
935
    if (t != null)
936
        t.suspend();
937
  }
938
 
939
  /**
940
   * Set this Thread's priority. There may be a security check,
941
   * <code>checkAccess</code>, then the priority is set to the smaller of
942
   * priority and the ThreadGroup maximum priority.
943
   *
944
   * @param priority the new priority for this Thread
945
   * @throws IllegalArgumentException if priority exceeds MIN_PRIORITY or
946
   *         MAX_PRIORITY
947
   * @throws SecurityException if you cannot modify this Thread
948
   * @see #getPriority()
949
   * @see #checkAccess()
950
   * @see ThreadGroup#getMaxPriority()
951
   * @see #MIN_PRIORITY
952
   * @see #MAX_PRIORITY
953
   */
954
  public final synchronized void setPriority(int priority)
955
  {
956
    checkAccess();
957
    if (priority < MIN_PRIORITY || priority > MAX_PRIORITY)
958
      throw new IllegalArgumentException("Invalid thread priority value "
959
                                         + priority + ".");
960
    priority = Math.min(priority, group.getMaxPriority());
961
    VMThread t = vmThread;
962
    if (t != null)
963
        t.setPriority(priority);
964
    else
965
        this.priority = priority;
966
  }
967
 
968
  /**
969
   * Returns a string representation of this thread, including the
970
   * thread's name, priority, and thread group.
971
   *
972
   * @return a human-readable String representing this Thread
973
   */
974
  public String toString()
975
  {
976
    return ("Thread[" + name + "," + priority + ","
977
            + (group == null ? "" : group.getName()) + "]");
978
  }
979
 
980
  /**
981
   * Clean up code, called by VMThread when thread dies.
982
   */
983
  synchronized void die()
984
  {
985
    group.removeThread(this);
986
    vmThread = null;
987
    locals = null;
988
  }
989
 
990
  /**
991
   * Returns the map used by ThreadLocal to store the thread local values.
992
   */
993
  static Map getThreadLocals()
994
  {
995
    Thread thread = currentThread();
996
    Map locals = thread.locals;
997
    if (locals == null)
998
      {
999
        locals = thread.locals = new WeakHashMap();
1000
      }
1001
    return locals;
1002
  }
1003
}

powered by: WebSVN 2.1.0

© copyright 1999-2025 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.