JAVA深化篇_28—— 線程使用之終止線程的典型方式以及線程休眠【附有詳細說明及代碼】
線程的使用
終止線程的典型方式
終止線程我們一般不使用JDK提供的stop()/destroy()方法(它們本身也被JDK廢棄了)。通常的做法是提供一個boolean型的終止變量,當這個變量置為false,則終止線程的運行。
終止線程的典型方法
public class StopThread implements Runnable {
//定義一個生死牌
private boolean flag = true;
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 線程開始");
int i= 0;
while(flag){
System.out.println(Thread.currentThread().getName()+" "+i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" 線程結束");
}
public void stop(){
//生死牌改變,調用這個方法時,線程死亡
this.flag = false;
}
public static void main(String[] args)throws Exception {
System.out.println("主線程開始");
StopThread st = new StopThread();
Thread t1 = new Thread(st);
t1.start();
System.in.read();
st.stop();
System.out.println("主線程結束");
}
}
線程休眠
sleep()方法:可以讓正在運行的線程進入阻塞狀態,直到休眠時間滿了,進入就緒狀態。sleep方法的參數為休眠的毫秒數。
public class SleepThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 線程開始");
for(int i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
try {
//線程休眠1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" 線程結束");
}
public static void main(String[] args) {
System.out.println("主線程開始");
Thread t = new Thread(new SleepThread());
t.start();
System.out.println("主線程結束");
}
}
浙公網安備 33010602011771號