Java线程(Thread)中join、sleep、interrupt、yield等方法总结

join简单使用

我们在T1线程的环境下,调用T2线程的join方法,那么T1线程将会等待T2线程结束后继续执行。也可以传入指定的等待时间,等待时间过后,不管T2线程有没有结束,T1线程将进行执行。
代码如下:

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(() -> {
        try {
            System.out.println("t1 start~");
            Thread.sleep(1000);
            System.out.println("t1 end~");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }, "t1");
    t1.start();
    System.out.println("main start~");
    t1.join();
    System.out.println("main end~");
}

sleep简单使用

让当前线程休眠指定的时间,同时让出CPU给其它线程。自身将处于阻塞状态。

join和sleep的相同点

1.调用这两个方法的线程对象都会处于等待状态。
2.都可能抛出InterruptedException异常

interrupt

调用此方法时:
若线程处于阻塞状态(调用了sleep,join,wait),则会抛出InterruptException异常。并清除打断标记。(一个boolean变量,标识此线程是否被打断)
若线程处于正常运行状态,则设置打断标志为true
实例代码(模拟每隔一段时间进行数据收集等操作):

public static void main(String[] args) throws InterruptedException {
    Thread t1 = new Thread(() -> {
        while (true) {
            boolean interrupted = Thread.currentThread().isInterrupted();
            if (interrupted) {
                System.out.println("被打断后的逻辑处理");
                break;
            }
            try {
                Thread.sleep(100);
                System.out.println("正常的逻辑处理");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }, "t1");
    t1.start();
    Thread.sleep(1000);
    t1.interrupt();
}

yield

试图让出CPU的使用权,但不保证一定能让出。
当前线程由Running变成Runnable.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值