Thread sleep方法

本文介绍Java中线程的sleep方法及其应用场景,并详细解释线程中断的概念、使用方式及其实现机制。

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

sleep方法就是暂停执行一会。这可以让其他线程获得执行时间。

也可以用来pacing,缓步,比如下面:

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}
注意到:sleep会抛出Inter乳品特定Exception,当线程sleep激活却被其他线程打断。这个例子没有定义另一个线程导致打断,不用用catch InterruptedException。


Interrupt


中断暗示线程应该停止手上工作去做其他事情。程序员决定线程如何响应中断,但是通常让线程停止。

一个线程发送中断通过调用被打断Thread对象的Interrupt。为了让中断机制正确工作,被中断的线程必须支持自己的中断


支持中断:

catch住InterruptedException,然返回,不进行处理,老子不干了。


for (int i = 0; i < importantInfo.length; i++) {
    // Pause for 4 seconds
    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        // We've been interrupted: no more messages.
        return;
    }
    // Print a message
    System.out.println(importantInfo[i]);
}

这么做的意义何在,

如果一个程序长期运行,中断不一定发生,就需要定期检查了



if (Thread.interrupted()) {
    throw new InterruptedException();
}

中断状态flag,中断标记是中断机制的实现。执行Thread.interrupt设置这个flag。当使用静态方法执行Thread.interrupted,中断状态清空。

非静态方法,inInterrupted,查询另一个线程状态,不会改变中断状态标记。


jon方法,等待这个线程die,里面的参数是等待时间,如果不设置,一直等啊。

join一般是在别的线程调用另一个线程的,作为判断吧。自己调用的是没有意义的。

给的例子是主线程调用



 Thread t = new Thread(new MessageLoop());
        t.start();


        threadMessage("Waiting for MessageLoop thread to finish");
        // loop until MessageLoop
        // thread exits
        while (t.isAlive()) {
            threadMessage("Still waiting...");
            // Wait maximum of 1 second
            // for MessageLoop thread
            // to finish.
            t.join();
            if (((System.currentTimeMillis() - startTime) > patience)
                  && t.isAlive()) {
                threadMessage("Tired of waiting!");
                t.interrupt();
                // Shouldn't be long now
                // -- wait indefinitely
                t.join();
            }
        }
        threadMessage("Finally!");


这些概念性的东西比较简单,关键还是同步啊。

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值