thread.java
来自「This is a resource based on j2me embedde」· Java 代码 · 共 1,528 行 · 第 1/4 页
JAVA
1,528 行
/* * @(#)Thread.java 1.145 06/10/10 * * Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */package java.lang;import java.security.AccessController;import java.security.AccessControlContext;import java.util.Map;import java.util.Collections;import sun.misc.CVM;import sun.misc.ThreadRegistry;import sun.security.util.SecurityConstants;/** * A <i>thread</i> is a thread of execution in a program. The Java * Virtual Machine allows an application to have multiple threads of * execution running concurrently. * <p> * Every thread has a priority. Threads with higher priority are * executed in preference to threads with lower priority. Each thread * may or may not also be marked as a daemon. When code running in * some thread creates a new <code>Thread</code> object, the new * thread has its priority initially set equal to the priority of the * creating thread, and is a daemon thread if and only if the * creating thread is a daemon. * <p> * When a Java Virtual Machine starts up, there is usually a single * non-daemon thread (which typically calls the method named * <code>main</code> of some designated class). The Java Virtual * Machine continues to execute threads until either of the following * occurs: * <ul> * <li>The <code>exit</code> method of class <code>Runtime</code> has been * called and the security manager has permitted the exit operation * to take place. * <li>All threads that are not daemon threads have died, either by * returning from the call to the <code>run</code> method or by * throwing an exception that propagates beyond the <code>run</code> * method. * </ul> * <p> * There are two ways to create a new thread of execution. One is to * declare a class to be a subclass of <code>Thread</code>. This * subclass should override the <code>run</code> method of class * <code>Thread</code>. An instance of the subclass can then be * allocated and started. For example, a thread that computes primes * larger than a stated value could be written as follows: * <p><hr><blockquote><pre> * class PrimeThread extends Thread { * long minPrime; * PrimeThread(long minPrime) { * this.minPrime = minPrime; * } * * public void run() { * // compute primes larger than minPrime * . . . * } * } * </pre></blockquote><hr> * <p> * The following code would then create a thread and start it running: * <p><blockquote><pre> * PrimeThread p = new PrimeThread(143); * p.start(); * </pre></blockquote> * <p> * The other way to create a thread is to declare a class that * implements the <code>Runnable</code> interface. That class then * implements the <code>run</code> method. An instance of the class can * then be allocated, passed as an argument when creating * <code>Thread</code>, and started. The same example in this other * style looks like the following: * <p><hr><blockquote><pre> * class PrimeRun implements Runnable { * long minPrime; * PrimeRun(long minPrime) { * this.minPrime = minPrime; * } * * public void run() { * // compute primes larger than minPrime * . . . * } * } * </pre></blockquote><hr> * <p> * The following code would then create a thread and start it running: * <p><blockquote><pre> * PrimeRun p = new PrimeRun(143); * new Thread(p).start(); * </pre></blockquote> * <p> * Every thread has a name for identification purposes. More than * one thread may have the same name. If a name is not specified when * a thread is created, a new name is generated for it. * * @author unascribed * @version 1.114, 05/17/00 * @see java.lang.Runnable * @see java.lang.Runtime#exit(int) * @see java.lang.Thread#run() * @since JDK1.0 */publicclass Thread implements Runnable { /* Make sure registerNatives is the first thing <clinit> does. */ /* private static native void registerNatives(); static { registerNatives(); } */ private char name[]; private int priority; private long eetop; /* Whether or not to single_step this thread. */ private boolean single_step; /* Whether or not the thread is a daemon thread. */ private boolean daemon = false; /* start() called. */ private boolean alive = false; /* start() called, keeps track that a thread can only be started once */ private boolean hasStartedOnce = false; /* Thread.stop() called. */ private boolean stillborn = false; /* Thread.interrupt() called. */ private boolean wasInterrupted = false; /* Locks for this class. */ private Object lock = new Object(); private static Object staticLock = new Object(); /* What will be run. */ private Runnable target; /* The group of this thread */ private ThreadGroup group; /* The context ClassLoader for this thread */ private ClassLoader contextClassLoader; /* The inherited AccessControlContext of this thread */ private AccessControlContext inheritedAccessControlContext; /* For autonumbering anonymous threads. */ private static int threadInitNumber; private static int nextThreadNum() { synchronized (staticLock) { return threadInitNumber++; } } /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; /* * InheritableThreadLocal values pertaining to this thread. This map is * maintained by the InheritableThreadLocal class. */ ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; /* * The requested stack size for this thread, or 0 if the creator did * not specify a stack size. It is up to the VM to do whatever it * likes with this number; some VMs will ignore it. */ private long stackSize; /** * The minimum priority that a thread can have. */ public final static int MIN_PRIORITY = 1; /** * The default priority that is assigned to a thread. */ public final static int NORM_PRIORITY = 5; /** * The maximum priority that a thread can have. */ public final static int MAX_PRIORITY = 10; /** * Returns a reference to the currently executing thread object. * * @return the currently executing thread. */ public static native Thread currentThread(); /** * Used to initialize the main thread. */ private static native void setCurrentThread(Thread main); /** * Causes the currently executing thread object to temporarily pause * and allow other threads to execute. */ public static native void yield(); /** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds. The thread * does not lose ownership of any monitors. * * @param millis the length of time to sleep in milliseconds. * @exception InterruptedException if another thread has interrupted * the current thread. The <i>interrupted status</i> of the * current thread is cleared when this exception is thrown. * @see java.lang.Object#notify() */ public static void sleep(long millis) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } sleep0(millis); } private static native void sleep0(long millis) throws InterruptedException; /** * Causes the currently executing thread to sleep (cease execution) * for the specified number of milliseconds plus the specified number * of nanoseconds. The thread does not lose ownership of any monitors. * * @param millis the length of time to sleep in milliseconds. * @param nanos 0-999999 additional nanoseconds to sleep. * @exception IllegalArgumentException if the value of millis is * negative or the value of nanos is not in the range * 0-999999. * @exception InterruptedException if another thread has interrupted * the current thread. The <i>interrupted status</i> of the * current thread is cleared when this exception is thrown. * @see java.lang.Object#notify() */ public static void sleep(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos >= 500000 || (nanos != 0 && millis == 0)) { millis++; } sleep0(millis); } /** * Initialize a Thread. * * @param g the Thread group * @param target the object whose run() method gets called * @param name the name of the new Thread * @param stackSize the desired stack size for the new thread, or * zero to indicate that this parameter is to be ignored. */ private void init(ThreadGroup g, Runnable target, String name, long stackSize) { /* We don't ever want locking on "lock" to fail, especially when * done during Thread.exit(). */ if (!sun.misc.CVM.objectInflatePermanently(lock)) { throw new OutOfMemoryError(); } Thread parent = currentThread(); if (parent == null) { // must be the main or an attached thread setCurrentThread(this); parent = this; } if (g == null) { /* Determine if it's an applet or not */ SecurityManager security = System.getSecurityManager(); /* If there is a security manager, ask the security manager what to do. */ if (security != null) { g = security.getThreadGroup(); } /* If the security doesn't have a strong opinion of the matter use the parent thread group. */ if (g == null) { g = parent.getThreadGroup(); } } /* checkAccess regardless of whether or not threadgroup is explicitly passed in. */ g.checkAccess(); g.addUnstarted(); this.group = g; this.daemon = parent.isDaemon(); this.name = name.toCharArray(); this.priority = parent.getPriority(); this.contextClassLoader = parent.contextClassLoader; this.inheritedAccessControlContext = AccessController.getContext(); this.target = target; setPriority(priority); if (parent.inheritableThreadLocals != null) this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); /* Stash the specified stack size in case the VM cares */ this.stackSize = stackSize; } private void init(ThreadGroup g, Runnable target, String name) { Thread parent = currentThread(); init(g, target, name, parent.getPriority()); } /** * Allocates a new <code>Thread</code> object. This constructor has * the same effect as <code>Thread(null, null,</code> * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is * a newly generated name. Automatically generated names are of the * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer. * * @see java.lang.Thread#Thread(java.lang.ThreadGroup, * java.lang.Runnable, java.lang.String) */ public Thread() { init(null, null, "Thread-" + nextThreadNum(), 0); } /** * Allocates a new <code>Thread</code> object. This constructor has * the same effect as <code>Thread(null, target,</code> * <i>gname</i><code>)</code>, where <i>gname</i> is * a newly generated name. Automatically generated names are of the * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer. * * @param target the object whose <code>run</code> method is called. * @see java.lang.Thread#Thread(java.lang.ThreadGroup, * java.lang.Runnable, java.lang.String) */ public Thread(Runnable target) { init(null, target, "Thread-" + nextThreadNum(), 0); }
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?