Thread类中的一些方法

1.yield:

 让步,表示当前线程愿意让出CPU资源给其他线程。而这种让步,不是绝对的,有可能执行了yield方法后,当前线程并没有真正让出CPU资源。
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
public static native void yield();

2.join:
 在某个位置等待一个线程执行超过某个时间或直到结束,可被中断。
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) { // 如果millis为0,则一直等待,直到等待的线程结束
       while (isAlive()) {
           wait(0);
       }
   } else {
       while (isAlive()) {
           long delay = millis - now;
           if (delay <= 0) {
               break;
           }
           wait(delay);
           now = System.currentTimeMillis() - base; // 减小误差
       }
   }
}

3.start:
 开始一个线程的执行,不能重复调用start。调用此方法后,由JVM执行线程的run方法。直接调用run方法,相当于在调用线程中顺序执行,而不是开启一个新线程。
public synchronized void start() {
   if (threadStatus != 0)
       throw new IllegalThreadStateException();

   group.add(this);

   boolean started = false;
   try {
       start0();
       started = true;
   } finally {
       try {
           if (!started) {
               group.threadStartFailed(this);
           }
       } catch (Throwable ignore) {
           /* do nothing. */
       }
   }
}

private native void start0();

4.sleep:
 令当前线程睡眠(暂定)一定时间。不释放锁,可被中断。常用的是TimeUnit中的sleep方法(实际上就是调用Thread的sleep方法)。
public static native void sleep(long millis) throws InterruptedException;

5.优先级:
 Java线程中有10个优先级(1-10),对应不同操作系统支持的不同优先级。可通过setPriority方法设置线程优先级。某些平台上线程优先级可能不会发生作用。Thread中定义了三个优先级静态变量。
public final static int MIN_PRIORITY = 1; // 最小优先级
public final static int NORM_PRIORITY = 5; // 默认优先级
public final static int MAX_PRIORITY = 10; // 最大优先级

6.守护(后台)线程:
 Java中有用户线程和守护线程,平时我们创建的线程都是用户线程,守护线程用来做一些并非必不可少的支持性后台工作。当所有用户线程结束后,程序退出,即使存在尚未执行完毕的守护线程,会导致守护线程中finally代码块不执行。默认创建的线程都是用户线程,可以在start方法前通过setDaemon方法设置守护线程。在守护线程中创建的子线程默认也是守护线程。
public class ThreadDemo2 {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(() -> {
            while (true) { // 无限循环,一秒打印一次线程名
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("daemon thread: " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        });
        t.setDaemon(true); // 设置为守护进程
        t.start();
        TimeUnit.SECONDS.sleep(5); // 主线程运行五秒后结束,不会等待其他守护线程结束程序就终止。
    }
}

7.中断:
 线程中断是指给线程设置中断标志。进入或正在某些阻塞方法(如sleep、Object.wait、join)上等待时,通过interrupt()方法设置中断标志会导致该线程抛出异常(InterrupteddException)并清空中断标志。interrupted()方法返回当前线程是否中断,如果是,返回true并清空中断标志。isInterrupted()方法仅返回是否中断,不会清空中断标志。
public class ThreadDemo2 {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(() -> {
            while (!Thread.interrupted()) { // 检测当前线程是否被中断
                long now = System.currentTimeMillis();
                while (System.currentTimeMillis() - now < 1000L) {
                    // 自旋一秒
                }
                System.out.println(Thread.currentThread().getName());
            }
            System.out.println("thread has bean interrupter. now: " + Thread.currentThread().isInterrupted()); // false,中断标志已经被清空
        });
        t.start();
        TimeUnit.SECONDS.sleep(5);
        t.interrupt(); // 设置线程中断标志
    }
}

8.线程异常捕获:
 线程中异常不能在run方法之外捕获。Java提供了UncaughtExceptionHandler接口帮助我们处理异常。
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("exception from thread: " + t);
        System.out.println("exception msg: " + e.getMessage());
    }
}

public class ThreadDemo2 {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(() -> {
            throw new RuntimeException("runtime exception!");
        });
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        t.start();
    }
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值