-
sleep最好使用在run方法的內部,因爲寫在run方法內部可以讓該線程休眠.
-
既然在main方法中不能將本指定線程休眠,那sleep一般怎麼用呢?
1.一般在想要睡眠線程的run()方法中讓當前線程休眠,因爲之所以會有線程,就是多個線程操作同一資源,只要在資源操作的run( )方法中使用sleep比較有意義。
2.如果是想交替使用,那麼使用wait + notify 結合使用
3.如果是等待線程的結果,那麼就使用join的方式 -
sleep究竟是讓哪一個線程休眠?
1.main方法中調用某一個線程類的對象t.sleep(),睡眠的不是t,而是調用sleep方法時所在類的main線程。在Runner1的run()中不寫sleep(),在主線程中寫Runner1.sleep(5000)時,結果不是Runner1睡眠,還是主線程睡眠, -
需要在run方法內部使用sleep方法讓該線程休眠,代碼如下:
public class Thread1 {
public static void main(String[] args) {
Runner1 r1 = new Runner1();
Thread t = new Thread(r1);
t.start();
for (int i = 0; i < 3; i++) {
System.out.println("main thread :"+i);
}
}
}
class Runner1 implements Runnable{
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
System.out.println("Runner1 : " + i);
}
}
}
結果:
main thread :0
main thread :1
main thread :2
----------------- 此處睡眠5秒,5秒後出現以下:
Runner1 : 0
Runner1 : 1
Runner1 : 2
- sleep方法只能讓當前線程睡眠,調用某一個線程類的對象t.sleep(),睡眠的不是t,而是sleep所在類的main線程,代碼如下:
public class Thread1 {
public static void main(String[] args) {
Runner1 r = new Runner1();
r.start();
try {
Runner1.sleep(5000); //此處是類名.sleep()
System.out.println("當前運行的線程名稱: "+ Runner1.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
System.out.println("main thread :"+i);
}
}
}
class Runner1 extends Thread{
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("Runner1 : " + i);
}
}
}
結果:
Runner1 : 0
Runner1 : 1
Runner1 : 2
--------------------------------- 此處睡眠5秒,5秒後出現以下:
當前運行的線程名稱: main
main thread :0
main thread :1
main thread :2
注意
- sleep方法是Thread類的靜態方法,直接使用Thread.sleep()就可以調用
- 在Java中,sleep方法的定義上使用了throws,所以在使用sleep方法時,一定要用try catch。
用博客見證成長,用行動證明我在努力。
如果你有緣看到我博客,對你有幫助、喜歡博客內容,請“點贊” “評論”“收藏”
一鍵三連哦!