sleep()
sleep是一个静态的本地方法,主要作用是使这个线程休眠一定时间,sleep的方法声明是这样的:
public static native void sleep(long millis) throws InterruptedException;
在使用的时候我们可以采取这样的方式。
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
方法中的参数1000代表的是休眠1秒,这个方法可以让我们很明显的观察多线程的变化。比如之前的代码可以改成:
public class Main {
public static void main(String[] args){
Thread thread1=new Thread(new TheThread());
Thread thread2=new Thread(new TheThread());
Thread thread3=new Thread(new TheThread());
thread1.start();
thread2.start();
thread3.start();
System.out.println("Main");
}
}
class TheThread implements Runnable{
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId() + ":" + i);
}
}
}
运行以上程序,查看结果
本文详细介绍了Java中Thread.sleep()方法的使用方法及其在多线程编程中的应用。通过具体示例展示了如何让线程暂停指定的时间,以及如何观察到多线程执行时的行为变化。
32

被折叠的 条评论
为什么被折叠?



