一、通過sleep方法睡眠
在指定的毫秒數內讓當前正在執行的線程休眠(暫停執行)。該線程不丟失任何監視器的所屬權。
二、線程優先級
線程具有優先級,范圍為1-10。
MAX_PRIORITY
線程可以具有的最高優先級。int類型,值為10.
MIN_PRIORITY
線程可以具有的最低優先級。int類型,值為1.
NORM_PRIORITY
分配給線程的默認優先級。int類型,值為5.
可以通過setPriority()設置線程的優先級。
三、yield方法讓出cpu
yield方法線程高風亮節讓出CPU一次。
四、停止線程的方法
stop()方法已經被棄用,原因是不太安全。API文檔中給出了具體的詳細解釋。
通過interrupted()方法打斷線程。不推薦。
通過共享變量結束run()方法,進而停止線程。如實例
public class ThreadInterrupt {public static void main(String []args){Runner run = new Runner();run.start();try {Thread.sleep(10000);} catch (InterruptedException e) {// TODO Auto-generated catch block }//run.stop();//已經廢棄的方法,不建議使用,過于粗暴//run.interrupt(); //拋出異常,但是在異常處理中寫業務顯然不合適,不建議使用run.flag=false;//建議使用的停止線程的方法 } }class Runner extends Thread{boolean flag = true;public void run(){/* while(true){System.out.println(new Date()+"----");try {sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blockSystem.out.println("Interrupted");return;}}*/while(flag){System.out.println(new Date()+"----");try {sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blockSystem.out.println("Interrupted");return;}}} }
五、Thread的sleep()方法與Object類的wait()方法比較
sleep()方法使線程休眠一定時間,休眠期間線程依然擁有之前獲得的鎖。而wait()方法使線程處于等待,等待期間線程不再擁有之前獲得的鎖。當其他進程通過notify喚醒進程后,線程重新去搶資源的鎖。wait()方法一般與notify()或notifyAll()方法一起出現。