Thread.sleep(long millis)和Thread.sleep(long millis, int nanos)
靜態方法
強制當前正在執行的線程休眠(
暫停執行),以“減慢線程”。
當線程睡眠時,它睡在某個地方,在蘇醒之前不會返回到可運行狀態。
當睡眠時間到期,則返回到可運行狀態。
線程睡眠的原因:
線程執行太快,或者需要強制進入下一輪,因為Java規范不保證合理的輪換。
睡眠的實現:調用靜態方法。
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
睡眠的位置:為了讓其他線程有機會執行,可以將Thread.sleep()的調用
放線程run()之內。這樣才能保證該線程執行過程中會睡眠。
public class TestSleep {
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("TestSleep");
t1.start();
for(int i=0 ; i <10; i++)
System.out.println("I am Main Thread");
}
}
class MyThread2 extends Thread {
MyThread2(String s) {
super(s);
}
public void run() {
for(int i = 1; i <= 10; i++) {
System.out.println("I am "+ getName());
try {
sleep(1000); //暫停,每一秒輸出一次
}catch (InterruptedException e) {
return;
}
}
}
}
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("TestSleep");
t1.start();
for(int i=0 ; i <10; i++)
System.out.println("I am Main Thread");
}
}
class MyThread2 extends Thread {
MyThread2(String s) {
super(s);
}
public void run() {
for(int i = 1; i <= 10; i++) {
System.out.println("I am "+ getName());
try {
sleep(1000); //暫停,每一秒輸出一次
}catch (InterruptedException e) {
return;
}
}
}
}
注意:
1、線程睡眠是幫助所有線程獲得運行機會的最好方法。
2、線程睡眠到期自動蘇醒,並返回到可運行狀態,不是運行狀態。
sleep()中指定的時間是線程不會運行的最短時間。因此,sleep()方法不能保證該線程睡眠到期后就開始執行。
3、sleep()是靜態方法,只能控制當前正在運行的線程。
實例二:一個計數器,計數到100,在每個數字之間暫停1秒,每隔10個數字輸出一個字符串
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
if ((i) % 10 == 0) {
System.out.println("-------" + i);
}
System.out.print(i);
try {
Thread.sleep(1000);
System.out.print(" 線程睡眠1秒!\n");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
for (int i = 0; i < 100; i++) {
if ((i) % 10 == 0) {
System.out.println("-------" + i);
}
System.out.print(i);
try {
Thread.sleep(1000);
System.out.print(" 線程睡眠1秒!\n");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new MyThread().start();
}
}
new MyThread().start();
}
}
