您的位置:首页 > 编程语言 > Java开发

java线程sleep的基本用法

2013-11-14 15:14 232 查看
import java.util.Date;

public class TestSleep {

public static void main(String[] args) {
Runnable a = new Thread1();
Thread t = new Thread(a);
t.start();
try {
Thread.sleep(10000);//在哪个线程里面的sleep方法,就是睡眠了哪个线程
} catch (InterruptedException e) {
}
t.interrupt();

}

}
//线程的sleep方法是静态的,可以通过Thread.sleep();直接调用
class Thread1 implements Runnable {

@Override
public void run() {
while (true) {
System.out.println("====" + new Date() + "=====");
try {
Thread.sleep(1000);//在哪个线程里面的sleep方法,就是睡眠了哪个线程
} catch (InterruptedException e) {
return;
}
}
}

}

class Thread2 extends Thread {
public void run() {
while (true) {
System.out.println("====" + new Date() + "=====");
try {
sleep(1000);//调用本身的sleep方法,非静态方法可以调用静态方法,静态方法需要对象调用非静态方法
} catch (InterruptedException e) {
return;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐