Thread API(一)

本文详细介绍了Java中线程的控制方法,包括sleep、yield和优先级设置等。sleep方法让线程休眠指定时间,期间不会释放锁;yield方法提示线程愿意放弃CPU资源,但不一定成功;线程优先级在1到10之间,默认为5,优先级高的线程更可能被调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值