一、線程的強制運行
二、線程的休眠
一、線程的強制運行
在線程操作中,可以使用 join() 方法讓一個線程強制運行,線程強制運行期間,其他線程無法運行,必須等待此線程完成之后才可以繼續執行
class MyThread implements Runnable{//實現 Runnable 接口
public void run(){//覆寫 Thread 類中的 run() 方法
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()
+ "運行 --> " + i);//取得當前線程的名稱
}
}
}
public class Root{
public static void main(String[] args) {
MyThread my = new MyThread();//定義 Runnable 子類對象
Thread t = new Thread(my,"線程");//實例化 Thread 對象
t.start();//啟動線程
for(int i=0;i<6;i++){
if(i>2){
try {
t.join();//線程 t 進行強制運行
}catch (Exception e){}//需要進行異常處理
}
System.out.println("Main 線程運行 --> " + i);
}
}
}
二、線程的休眠
在程序中允許一個線程進行暫時的休眠,直接使用 Thread.sleep() 方法即可實現休眠
class MyThread implements Runnable{//實現 Runnable 接口
public void run(){//覆寫 Thread 類中的 run() 方法
for(int i=0;i<5;i++){
try{
Thread.sleep(2);//線程休眠
}catch (Exception e){}
System.out.println(Thread.currentThread().getName()
+ "運行 --> " + i);//取得當前線程的名稱
}
}
}
public class Root{
public static void main(String[] args) {
MyThread my = new MyThread();//定義 Runnable 子類對象
Thread t = new Thread(my,"線程");//實例化 Thread 對象
t.start();//啟動線程
}
}