一、中斷線程
1.Thread.sleep()
讓線程進入睡眠狀态,放棄CPU的占用暫停若幹毫秒
使用方法:
public class runable implements Runnable {
@Override
public void run() {
for(int i=1;i<100;i++){
System.out.println("first Runnable——>"+i);
try {
Thread.sleep(200);//設定睡眠時間為200毫秒,
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
2.Thread.yidld()
讓線程放棄CPU的占用,但是繼續搶占CPU
二、設定線程的優先級
預設優先級是5,最大優先級是10,最小優先級是1
1.getPriority()
得到目前程序的優先級
2.setPriority()
設定目前線程的優先級
public class main {
public static void main(String[] args) throws InterruptedException {
//實作接口
runable ra=new runable();
//生成Thread對象,并将接口對象作為參數
Thread t=new Thread(ra);
//sleep()方法使用
t.sleep(200);
//得到目前優先級
int temp=t.getPriority();
System.out.println("預設優先級:"+temp);
//設定最高優先級并輸出
t.setPriority(Thread.MAX_PRIORITY);
temp=t.getPriority();
System.out.println("最高優先級:"+temp);
//設定最低優先級,并輸出
t.setPriority(Thread.MIN_PRIORITY);
temp=t.getPriority();
System.out.println("最低優先級:"+temp);
}
}