start()
進入待命狀態 可執行狀態
run()
執行狀態
wait()
進入等待狀態
notify()
讓某個等待中的執行緒回到待命狀態
notifyAll()
讓該物件的所有等待的執行緒 回到待命狀態
interrupt()
設定該執行緒的中斷旗標 拋出例外
sleep()單位毫秒
使執行緒進入休眠狀態 休眠時間到後回到待命狀態
join()
結合兩個執行緒
設置優先權:
Thread.MIN_PRIORITY 1
Thread.MAX_PRIORITY 10
Thread.NORM_PRIORITY 5
setPriority()
getPriority()
yield() 讓其他執行緒有執行的機會
Thread.currentThread().getName() 取得目前執行執行緒的名稱
參考: http://programming.im.ncnu.edu.tw/J_index.html
繼承Thread寫法
public class ThreadExample1 extends Thread {
public void run() { // override Thread's run()
System.out.println("Here is the starting point of Thread.");
for (;;) { // infinite loop to print message
System.out.println("User Created Thread");
}
}
public static void main(String[] argv) {
Thread t = new ThreadExample1(); // 產生Thread物件
t.start(); // 開始執行t.run()
for (;;) {
System.out.println("Main Thread");
}
}
}
實現Runnable介面寫法
public class ThreadExample2 implements Runnable {
public void run() { // implements Runnable run()
System.out.println("Here is the starting point of Thread.");
for (;;) { // infinite loop to print message
System.out.println("User Created Thread");
}
}
public static void main(String[] argv) {
Thread t = new Thread(new ThreadExample2()); // 產生Thread物件
t.start(); // 開始執行Runnable.run();
for (;;) {
System.out.println("Main Thread");
}
}
}
沒有留言:
張貼留言