线程--中断(interruput),等待线程结束(join),休眠(sleep)

本文详细介绍了Java线程中的中断机制,包括通过`interrupt()`方法通知线程中断,并讨论了线程如何响应中断,如`InterruptedException`的处理。此外,还阐述了线程等待`join()`方法的使用以及线程休眠`sleep()`方法的注意事项。

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

1.线程中断
(1)通过thread 对象调用 interrupt 方法通知线程中断.
(2). thread 收到通知的方式有两种:

  1. 如果线程调用了 wait/join/sleep 等方法而阻塞挂起,则以 InterruptedException 异常的形式通知,清除中断标志
  2. 否则,只是内部的一个中断标志被设置,thread 可以通过
    (设置中断标志:true; 清除中断标志:false)
    ①. Thread.interrupted() 判断当前线程的中断标志被设置,清除中断标志
    Thread.currentThread().isInterrupted() 判断指定线程的中断标志被设置,不清除中断标志

具体方法:
public void interrupt() :中断对象关联的线程,如果线程正在阻塞,则以异常方式通知,否则设置标志位
public static boolean interrupted() :判断当前线程的中断标志位是否设置,调用后清除标志位
public boolean isInterrupted(): 判断对象关联的线程的标志位是否设置,调用后不清除标志位

注意:调用interrupt() 方法,只是通知线程要终止, 至于线程是否终止,需要线程自行判断.

public static void main(String[] main) throws InterruptedException {
         
          Thread t=  new Thread( new Runnable() {
                @Override
                public void run() {
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println(Thread.currentThread().isInterrupted());
                    }
                }
            });
                t.start();
                Thread.sleep(1);
                t.interrupt();
        }



-------
2.线程等待
当需要等一个线程执行完后,才能进行接下来的操作时,就得调用 join() 方法,等待一个线程结束.

方法:
public void join() 等待线程结束
public void join(long millis) 等待线程结束,最多等 millis(毫秒)
public void join(long millis, int nanos) 同理,但可以更高精度

  public static void main(String[] args) throws InterruptedException {
        
          Thread t1=  new Thread(()->{
              System.out.println("A");
            });
          Thread t2=  new Thread(()->{
              System.out.println("B");
            });
          Thread t3=  new Thread(()->{
              System.out.println("C");
            });
        t1.start();
        t1.join();
                 等t1执行结束后,再执行t2;下同.//所以ABC会按顺序打印
        t2.start();
        t2.join();
        
        t3.start();
        t3.join();
        
    }

在这里插入图片描述
如果不加 join() 方法 ,那么ABC就不是按顺序打印了
在这里插入图片描述
3.线程休眠
在这里插入图片描述
注意: 因为线程的调度是不可控的,所以,这个方法只能保证线程休眠时间是大于
等于所设置的休眠时间的。

  public static void main(String[] args) throws InterruptedException {
            System.out.println(System.currentTimeMillis());

            Thread.sleep(3 * 1000);//休眠3000毫秒;

            System.out.println(System.currentTimeMillis());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值