小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

java一個多線程的經典例子

 CevenCheng 2011-01-13

java一個多線程的經典例子

文章分類:Java編程 關鍵字: java一個多線程的經典例子
import java.io.*; 

//多線程編程 
public class MultiThread   

public static void main(String args[]) 

System.out.println("我是主線程!"); 
//下面創(chuàng)建線程實例thread1 
ThreadUseExtends thread1=new ThreadUseExtends(); 
//創(chuàng)建thread2時以實現(xiàn)了Runnable接口的THhreadUseRunnable類實例為參數 
Thread thread2=new Thread(new ThreadUseRunnable(),"SecondThread"); 
thread1.start();//啟動線程thread1使之處于就緒狀態(tài) 
//thread1.setPriority(6);//設置thread1的優(yōu)先級為6 
//優(yōu)先級將決定cpu空出時,處于就緒狀態(tài)的線程誰先占領cpu開始運行 
//優(yōu)先級范圍1到10,MIN_PRIORITY,MAX_PRIORITY,NORM_PAIORITY 
//新線程繼承創(chuàng)建她的父線程優(yōu)先級,父線程通常有普通優(yōu)先級即5NORM_PRIORITY 
System.out.println("主線程將掛起7秒!"); 
try 

Thread.sleep(7000);//主線程掛起7秒 

catch (InterruptedException e) 

return; 

System.out.println("又回到了主線程!"); 
if(thread1.isAlive()) 
{   
thread1.stop();//如果thread1還存在則殺掉他 
System.out.println("thread1休眠過長,主線程殺掉了thread1!"); 

else 
System.out.println("主線程沒發(fā)現(xiàn)thread1,thread1已醒順序執(zhí)行結束了!"); 
thread2.start();//啟動thread2 
System.out.println("主線程又將掛起7秒!"); 
try 

Thread.sleep(7000);//主線程掛起7秒 

catch (InterruptedException e) 

return; 

System.out.println("又回到了主線程!"); 
if(thread2.isAlive()) 
{   
thread2.stop();//如果thread2還存在則殺掉他 
System.out.println("thread2休眠過長,主線程殺掉了thread2!"); 

else 
System.out.println("主線程沒發(fā)現(xiàn)thread2,thread2已醒順序執(zhí)行結束了!"); 
System.out.println("程序結束按任意鍵繼續(xù)!"); 
try 

System.in.read(); 

catch (IOException e) 

System.out.println(e.toString()); 




}//main 
}//MultiThread 




class ThreadUseExtends extends Thread 
//通過繼承Thread類,并實現(xiàn)它的抽象方法run() 
//適當時候創(chuàng)建這一Thread子類的實例來實現(xiàn)多線程機制 
//一個線程啟動后(也即進入就緒狀態(tài))一旦獲得CPU將自動調用它的run()方法 




ThreadUseExtends(){}//構造函數 
public void run() 

System.out.println("我是Thread子類的線程實例!"); 
System.out.println("我將掛起10秒!"); 
System.out.println("回到主線程,請稍等,剛才主線程掛起可能還沒醒過來!"); 
try 

sleep(10000);//掛起5秒 

catch (InterruptedException e) 

return; 

//如果該run()方法順序執(zhí)行完了,線程將自動結束,而不會被主線程殺掉 
//但如果休眠時間過長,則線程還存活,可能被stop()殺掉 






class ThreadUseRunnable implements Runnable 
//通過實現(xiàn)Runnable接口中的run()方法,再以這個實現(xiàn)了run()方法的類 
//為參數創(chuàng)建Thread的線程實例 

//Thread thread2=new Thread(this); 
//以這個實現(xiàn)了Runnable接口中run()方法的類為參數創(chuàng)建Thread類的線程實例 
ThreadUseRunnable(){}//構造函數 
public void run() 

System.out.println("我是Thread類的線程實例并以實現(xiàn)了Runnable接口的類為參數!"); 
System.out.println("我將掛起1秒!"); 
System.out.println("回到主線程,請稍等 jn0-120 e20-040 ,剛才主線程掛起可能還沒醒過來!"); 
try 

Thread.sleep(1000);//掛起5秒 

catch (InterruptedException e) 

return; 

//如果該run()方法順序執(zhí)行完了,線程將自動結束,而不會被主線程殺掉 
//但如果休眠時間過長,則線程還存活,可能被stop()殺掉 





//該程序可做的修改如改休眠時間或優(yōu)先級setPriority() 

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多