sleep 方法介绍
sleep(long millis);
sleep(long millis, int nanos);
休眠时线程不会放弃monitor锁的所有权,只导致当前线程进入指定时间休眠,没有CPU时间片的消耗,另一个线程调用interrupt会捕捉到中断信号。
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);
}
使用TimeUnit 替代Thread.sleep
TimeUnit 更加清晰明了。
Thread.sleep(1);
TimeUnit.HOURS.sleep(1);
TimeUnit.MINUTES.sleep(1);
TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(1);
yield 方法介绍
会提醒调度器愿意放弃当前CPU资源,如果CPU资源不紧张,则会忽略这种提醒,提醒成功线程从running进入runnable。yield方法不能保证一定会使线程从运行状态中退出,所以另一个线程调用interrupt不会捕捉到中断信号。
线程优先级介绍
public final void setPriority(int newPriority);//设置线程优先级
public final int getPriority();//获取线程优先级
线程的优先级范围:1~10,默认的优先级与父线程保持一致,一般情况是5(因为main线程是5),如果指定的优先级大于线程所在group的优先级,那么制定的优先级将会失效,取而代之的是group的最大优先级。理论上优先级越高获得被CPU调度的机会也就越大。
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
//MAX_PRIORITY=10 MIN_PRIORITY=1
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
Thread currentThread();//获取当前线程
setContextClassLoader(ClassLoader cl); //设置线程上下文类加载器
ClassLoader getContextClassLoader();//获取线程上下文类加载器
public void setContextClassLoader(ClassLoader cl) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("setContextClassLoader"));
}
contextClassLoader = cl;
}
@CallerSensitive
public ClassLoader getContextClassLoader() {
if (contextClassLoader == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader.checkClassLoaderPermission(contextClassLoader,
Reflection.getCallerClass());
}
return contextClassLoader;
}