標籤:sse name rand 精度 r.java ext public jin 編譯
Java 給多線程編程提供了內建的支援。一個多線程程式包含兩個或多個能並發啟動並執行部分。程式的每一部分都稱作一個線程,並且每個線程定義了一個獨立的執行路徑。
多線程是多任務的一種特別的形式,但多線程使用了更小的資源開銷。
這裡定義和線程相關的另一個術語 - 進程:一個進程包括由作業系統分配的記憶體空間,包含一個或多個線程。一個線程不能獨立的存在,它必須是進程的一部分。一個進程一直運行,直到所有的非守候線程都結束運行後才能結束。
多線程能滿足程式員編寫高效率的程式來達到充分利用 CPU 的目的。
一個線程的生命週期
線程是一個動態執行的過程,它也有一個從產生到死亡的過程。
顯示了一個線程完整的生命週期。
建立狀態:
使用 new 關鍵字和 Thread 類或其子類建立一個線程對象後,該線程對象就處於建立狀態。它保持這個狀態直到程式 start() 這個線程。
就緒狀態:
當線程對象調用了start()方法之後,該線程就進入就緒狀態。就緒狀態的線程處於就緒隊列中,要等待JVM裡線程調度器的調度。
運行狀態:
如果就緒狀態的線程擷取 CPU 資源,就可以執行 run(),此時線程便處於運行狀態。處於運行狀態的線程最為複雜,它可以變為阻塞狀態、就緒狀態和死亡狀態。
阻塞狀態:
如果一個線程執行了sleep(睡眠)、suspend(掛起)等方法,失去所佔用資源之後,該線程就從運行狀態進入阻塞狀態。在睡眠時間已到或獲得裝置資源後可以重新進入就緒狀態。可以分為三種:
等待阻塞:運行狀態中的線程執行 wait() 方法,使線程進入到等待阻塞狀態。
同步阻塞:線程在擷取 synchronized 同步鎖失敗(因為同步鎖被其他線程佔用)。
其他阻塞:通過調用線程的 sleep() 或 join() 發出了 I/O 請求時,線程就會進入到阻塞狀態。當sleep() 狀態逾時,join() 等待線程終止或逾時,或者 I/O 處理完畢,線程重新轉入就緒狀態。
死亡狀態:
一個運行狀態的線程完成任務或者其他終止條件發生時,該線程就切換到終止狀態。
線程的優先順序
每一個 Java 線程都有一個優先順序,這樣有助於作業系統確定線程的調度順序。
Java 線程的優先順序是一個整數,其取值範圍是 1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY )。
預設情況下,每一個線程都會分配一個優先順序 NORM_PRIORITY(5)。
具有北京股票配資較高優先順序的線程對程式更重要,並且應該在低優先順序的線程之前分配處理器資源。但是,線程優先順序不能保證線程執行的順序,而且非常依賴於平台。
建立一個線程
Java 提供了三種建立線程的方法:
通過實現 Runnable 介面;
通過繼承 Thread 類本身;
通過 Callable 和 Future 建立線程。
通過實現 Runnable 介面來建立線程
建立一個線程,最簡單的方法是建立一個實現 Runnable 介面的類。
為了實現 Runnable,一個類只需要執行一個方法調用 run(),聲明如下:
public void run()
你可以重寫該方法,重要的是理解的 run() 可以調用其他方法,使用其他類,並聲明變數,就像主線程一樣。
在建立一個實現 Runnable 介面的類之後,你可以在類中執行個體化一個線程對象。
Thread 定義了幾個構造方法,下面的這個是我們經常使用的:
Thread(Runnable threadOb,String threadName);
這裡,threadOb 是一個實現 Runnable 介面的類的執行個體,並且 threadName 指定新線程的名字。
新線程建立之後,你調用它的 start() 方法它才會運行。
void start();
下面是一個建立線程並開始讓它執行的執行個體:
執行個體
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// 讓線程睡眠一會
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.bjrongjinhuiyin.com.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start();
}
}
編譯以上程式運行結果如下:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
通過繼承Thread來建立線程
建立一個線程的第二種方法是建立一個新的類,該類繼承 Thread 類,然後建立一個該類的執行個體。
繼承類必須重寫 run() 方法,該方法是新線程的進入點。它也必須調用 start() 方法才能執行。
該方法融金匯銀儘管被列為一種多線程實現方式,但是本質上也是實現了 Runnable 介面的一個執行個體。
執行個體
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// 讓線程睡眠一會
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2"); T2.start();
}
}
編譯以上程式運行結果如下:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread 方法
下表列出了Thread類的一些重要方法:
序號 方法描述
1 public void start()
使該線程開始執行;JAVA 虛擬機器調用該線程的 run 方法。
2 public void run()
如果該線程是使用獨立的 Runnable 運行物件建構的,則調用該 Runnable 對象的 run 方法;否則,該方法不執行任何操作並返回。
3 public final void setName(String name)
改變線程名稱,使之與參數 name 相同。
4 public final void setPriority(int priority)
更改線程的優先順序。
5 public final void setDaemon(boolean on)
將該線程標記為守護線程或使用者線程。
6 public final void join(long millisec)
等待該線程終止的時間最長為 millis 毫秒。
7 public void interrupt()
中斷線程。
8 public final boolean isAlive()
測試線程是否處於活動狀態。
測試線程是否處於活動狀態。 上述方法是被Thread對象調用的。下面的方法是Thread類的靜態方法。
序號 方法描述
1 public static void yield()
暫停當前正在執行的線程對象,並執行其他線程。
2 public static void sleep(long millisec)
在指定的毫秒數內讓當前正在執行的線程休眠(暫停執行),此操作受到系統計時器和發送器精度和準確性的影響。
3 public static boolean holdsLock(Object x)
若且唯若當前線程在指定的對象上保持監視器鎖時,才返回 true。
4 public static Thread currentThread()
返回對當前正在執行的線程對象的引用。
5 public static void dumpStack()
將當前線程的堆疊追蹤列印至標準錯誤流。
執行個體
如下的ThreadClassDemo 程式示範了Thread類的一些方法:
DisplayMessage.java 檔案代碼:
// 檔案名稱 : DisplayMessage.java
// 通過實現 Runnable 介面建立線程
public class DisplayMessage implements Runnable {
private String message;
public DisplayMessage(String message) {
this.message = message;
}
public void run() {
while(true) {
System.out.println(message);
}
}
}
GuessANumber.java 檔案代碼:
// 檔案名稱 : GuessANumber.java
// 通過繼承 Thread 類建立線程
public class GuessANumber extends Thread {
private int number;
public GuessANumber(int number) {
this.number = number;
}
public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println(" Correct!" + this.getName() + "in" + counter + "guesses.");
}
}
ThreadClassDemo.java 檔案代碼:
// 檔案名稱 : ThreadClassDemo.java
public class ThreadClassDemo {
public static void main(String [] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(bye); thread2.setPriority(Thread.MIN_PRIORITY); thread2.setDaemon(true); System.out.println("Starting goodbye thread..."); thread2.start(); System.out.println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try { thread3.join(); }catch(InterruptedException e) { System.out.println("Thread interrupted."); } System.out.println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); System.out.println("main() is ending...");
}
}
運行結果如下,每一次啟動並執行結果都不一樣。
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
通過 Callable 和 Future 建立線程
- 建立 Callable 介面的實作類別,並實現 call() 方法,該 call() 方法將作為線程執行體,並且有傳回值。
- 建立 Callable 實作類別的執行個體,使用 FutureTask 類來封裝 Callable 對象,該 FutureTask 對象封裝了該 Callable 對象的 call() 方法的傳回值。
- 使用 FutureTask 對象作為 Thread 對象的 target 建立並啟動新線程。
-
調用 FutureTask 對象的 get() 方法來獲得子線程執行結束後的傳回值。
執行個體
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args)
{
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" 的迴圈變數i的值"+i);
if(i==20)
{
new Thread(ft,"有傳回值的線程").start();
}
}
try
{
System.out.println("子線程的傳回值:"+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
Java 多線程編程