package ui.ins;
import java.io.IOException;
//多線程編程
public class MultiThread {
public static void main(String args[]) {
System.out.println("我是主線程!");
// 下面創建線程實例thread1
ThreadUseExtends thread1 = new ThreadUseExtends();
// 創建thread2時以實現了Runnable接口的THhreadUseRunnable類實例爲參數
Thread thread2 = new Thread(new ThreadUseRunnable(), "SecondThread");
thread1.start();// 啓動線程thread1使之處於就緒狀態
// thread1.setPriority(6);//設置thread1的優先級爲6
// 優先級將決定cpu空出時,處於就緒狀態的線程誰先佔領cpu開始運行
// 優先級範圍1到10,MIN_PRIORITY,MAX_PRIORITY,NORM_PAIORITY
// 新線程繼承創建她的父線程優先級,父線程通常有普通優先級即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("主線程沒發現thread1,thread1已醒順序執行結束了!");
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("主線程沒發現thread2,thread2已醒順序執行結束了!");
System.out.println("程序結束按任意鍵繼續!");
try {
System.in.read();
} catch (IOException e) {
System.out.println(e.toString());
}
}// main
}// MultiThread
class ThreadUseExtends extends Thread
// 通過繼承Thread類,並實現它的抽象方法run()
// 適當時候創建這一Thread子類的實例來實現多線程機制
// 一個線程啓動後(也即進入就緒狀態)一旦獲得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()方法順序執行完了,線程將自動結束,而不會被主線程殺掉
// 但如果休眠時間過長,則線程還存活,可能被stop()殺掉
}
}
class ThreadUseRunnable implements Runnable
// 通過實現Runnable接口中的run()方法,再以這個實現了run()方法的類
// 爲參數創建Thread的線程實例
{
// Thread thread2=new Thread(this);
// 以這個實現了Runnable接口中run()方法的類爲參數創建Thread類的線程實例
ThreadUseRunnable() {
}// 構造函數
public void run() {
System.out.println("我是Thread類的線程實例並以實現了Runnable接口的類爲參數!");
System.out.println("我將掛起1秒!");
System.out.println("回到主線程,請稍等,剛纔主線程掛起可能還沒醒過來!");
try {
Thread.sleep(1000);// 掛起5秒
} catch (InterruptedException e) {
return;
}
// 如果該run()方法順序執行完了,線程將自動結束,而不會被主線程殺掉
// 但如果休眠時間過長,則線程還存活,可能被stop()殺掉
}
}
// 該程序可做的修改如改休眠時間或優先級setPriority()