您的位置:首页 > 编程语言 > Java开发

java8类库简单了解(三)Runnable和Thread

2018-03-30 17:09 423 查看
1,Runnable接口源码如下:package java.lang;
/**
* @since JDK1.0
*/
@FunctionalInterface
public interface Runnable {
public abstract void run();
}以前没注意,这一看让笔者有点惊讶,极简爆了

2,Thread部分源码如下:package java.lang;
/**
* @since JDK1.0
*/
public
class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}

//volatile:禁制指令重排序(多线程方面相关),即在底层处理中保证先执行name[]
private volatile char name[];
private int priority;
private Thread threadQ;
private long eetop;

/**
* 线程可以拥有的最小优先级。
*/
public final static int MIN_PRIORITY = 1;

/**
* 分配给线程的默认优先级。
*/
public final static int NORM_PRIORITY = 5;

/**
* 线程可以拥有的最大优先级。
*/
public final static int MAX_PRIORITY = 10;

/**
* 返回对当前正在执行的线程对象的引用。
*/
public static native Thread currentThread();

/**
* 暂停当前线程的运行,yield()方法只能让同优先级的线程有执行的机会。
*/
public static native void yield();

/**
* 使当前线程休眠指定时间,暂停执行一段时间,让其他线程有机会继续执行,但它并不释放对象锁。也就是说如果有synchronized同步快,其他线程仍然不能访问共享数据。
*/
public static native void sleep(long millis) throws InterruptedException;

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++;
}

sleep(millis);
}

/**
* 分配一个新的Thread对象
*/
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}

/**
target:运行对象
* target - 启动此线程时调用其run方法的对象。 如果null ,这个类run方法什么都不做。
*/
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}

/**
* group - 线程组。 如果是null并且有一个安全管理员,那么该组由SecurityManager.getThreadGroup()决定 。
如果没有安全管理员或SecurityManager.getThreadGroup()返回null ,该组将设置为当前线程的线程组。
*/
public Thread(ThreadGroup group, Runnable target) {
init(group, target, "Thread-" + nextThreadNum(), 0);
}

/**
* name - 新线程的名称
*/
public Thread(String name) {
init(null, null, name, 0);
}

public Thread(ThreadGroup group, String name) {
init(group, null, name, 0);
}

public Thread(Runnable target, String name) {
init(null, target, name, 0);
}

/**
* 分配一个新的Thread对象,使其具有target作为其运行对象,具有指定的name作为其名称,属于group引用的线程组。
*/
public Thread(ThreadGroup group, Runnable target, String name) {
init(group, target, name, 0);
}

/**
* 分配一个新的Thread对象,以便它具有target作为其运行对象,将指定的name正如其名,以及属于该线程组由称作group ,并具有指定的堆栈大小 。
* @since 1.4
*/
public Thread(ThreadGroup group, Runnable target, String name,
long stackSize) {
init(group, target, name, stackSize);
}

/**
* 当前线程开始执行
*/
public synchronized void start() {

if (threadStatus != 0)
throw new IllegalThreadStateException();

/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);

boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}

private native void start0();

/**
* 线程的运行代码
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}

/**
* This method is called by the system to give a Thread
* a chance to clean up before it actually exits.
*/
private void exit() {
if (group != null) {
group.threadTerminated(this);
group = null;
}
/* Aggressively null out all reference fields: see bug 4006245 */
target = null;
/* Speed the release of some of these resources */
threadLocals = null;
inheritableThreadLocals = null;
inheritedAccessControlContext = null;
blocker = null;
uncaughtExceptionHandler = null;
}

/**
* 测试当前线程是否中断。该方法可以清除线程的中断状态 。
true如果当前线程已被中断; false否则。
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}

/**
* 测试当前线程是否中断。线程的中断状态不受此方法的影响。
true如果当前线程已被中断; false否则。
*/
public boolean isInterrupted() {
return isInterrupted(false);
}

/**
* 测试这个线程是否活着。
*/
public final native boolean isAlive();

/**
* 更改此线程的优先级。
*/
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}

/**
* 得到此线程的优先级。
*/
public final int getPriority() {
return priority;
}

/**
* 将此线程的名称更改为等于参数 name 。
*/
public final synchronized void setName(String name) {
checkAccess();
this.name = name.toCharArray();
if (threadStatus != 0) {
setNativeName(name);
}
}

/**
* 返回此线程的名称。
*/
public final String getName() {
return new String(name, true);
}

/**
* 等待这个线程死亡的时间最多为millis毫秒。 0的超时意味着永远等待。
*/
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;

if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}

if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}

/**
* 等待最多millis毫秒加上这个线程死亡的nanos纳秒。
*/
public final synchronized void join(long millis, int nanos)
throws InterruptedException {

if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}

if (nanos < 0 || n
4000
anos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}

if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}

join(millis);
}

/**
* 等待这个线程死亡。
*/
public final void join() throws InterruptedException {
join(0);
}

/**
* 将此线程标记为 daemon线程或用户线程。on - 如果 true ,将此线程标记为守护线程
*/
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}

/**
* 测试这个线程是否是守护线程。
*/
public final boolean isDaemon() {
return daemon;
}

/**
* 确定当前正在运行的线程是否有权限修改此线程。
*/
public final void checkAccess() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkAccess(this);
}
}

/**
* 返回此线程的字符串表示,包括线程的名称,优先级和线程组。
*/
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
return "Thread[" + getName() + "," + getPriority() + "," +
group.getName() + "]";
} else {
return "Thread[" + getName() + "," + getPriority() + "," +
"" + "]";
}
}

private static final RuntimePermission SUBCLASS_IMPLEMENTATION_PERMISSION =
new RuntimePermission("enableContextClassLoaderOverride");

/** cache of subclass security audit results */
/* Replace with ConcurrentReferenceHashMap when/if it appears in a future
* release */
private static class Caches {
/** cache of subclass security audit results */
static final ConcurrentMap<WeakClassKey,Boolean> subclassAudits =
new ConcurrentHashMap<>();

/** queue for WeakReferences to audited subclasses */
static final ReferenceQueue<Class<?>> subclassAuditsQueue =
new ReferenceQueue<>();
}

/**
* Verifies that this (possibly subclass) instance can be constructed
* without violating security constraints: the subclass must not override
* security-sensitive non-final methods, or else the
* "enableContextClassLoaderOverride" RuntimePermission is checked.
*/
private static boolean isCCLOverridden(Class<?> cl) {
if (cl == Thread.class)
return false;

processQueue(Caches.subclassAuditsQueue, Caches.subclassAudits);
WeakClassKey key = new WeakClassKey(cl, Caches.subclassAuditsQueue);
Boolean result = Caches.subclassAudits.get(key);
if (result == null) {
result = Boolean.valueOf(auditSubclass(cl));
Caches.subclassAudits.putIfAbsent(key, result);
}

return result.booleanValue();
}

/**
* 返回此线程的标识符。
* @since 1.5
*/
public long getId() {
return tid;
}

/**
* 返回此线程的状态。
* @since 1.5
*/
public State getState() {
// get current thread state
return sun.misc.VM.toThreadState(threadStatus);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: