做作業的第二題總結出幾種方法:
1、建立類的一個變數,有幾個線程對象,變數就是幾,然後在run()方法裡的try{}catch(InterruptedException e){}語句後面添上一個finally{synchronized(this){this.變數名--;}};這樣來鎖定,當每次執行時都會執行finally,從而變數一直減,當變數減到0時,然後再run()裡面的最後再添加一個判斷if(類名.變數名==0){輸出線程運行完畢!}我覺得這個適合多個線程對象還有同步線程 !
2、在main() 主函數裡面最後寫上一個迴圈,使條件永真,迴圈裡有一個判斷語句,判斷對象的getStatc()是否等於線程結束狀態Thread.State.TERMINATEED,如果等於就輸出線程運行完畢!並且跳出迴圈,當然這種只適合對象比較少的情況。
3、也是在main()函數裡寫上一個try{}catch(InterruptedException e){}語句.直接在try裡面寫上Thread.sleep(time);time是比最長時間的線程都大於等於的;這樣保證他們都執行完以後,再監視一下線程的狀態,當然不確定時間的話就填上一個永真迴圈,跟上面第2種方法一樣;
4、還有一種不符合編程的方法,雖然不符合,但是也能成功,就是直接在run()函數裡的try{}catch(InterruptedException e){}語句後面添上一個判斷語句,看線程的時間是否等於最長時間,當然這種是要前提下知道最長時間的;這個就不太適合用 了。
另外附於我寫的一個例子:
class A implements Runnable{
String str;
int delay;
static int n=0;
public A(String str,int delay){
this.str=str;
this.delay=delay;
}
public static void main(String[] args) {
Thread t1=new Thread(new A("A類對象1",1000));
t1.start();
Thread t2=new Thread(new A("B類對象1",2000));
t2.start();
try {
Thread.sleep(2000);
if(t1.getState()==Thread.State.TERMINATED&&t2.getState()==Thread.State.TERMINATED){
System.out.println("線程運行完畢 !");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
public void run() {
try {
Thread.sleep(delay);
System.out.println(str + "\t休眠時間為:" + delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
好就先總結到這兒吧!不知道我寫的你是否都看懂.