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]); } } }