<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # java 多線程 > 原文: [https://beginnersbook.com/2013/03/multithreading-in-java/](https://beginnersbook.com/2013/03/multithreading-in-java/) 在我們討論**多線程**之前,讓我們討論一下線程。線程是進程的輕量級最小部分,可以與同一進程的其他部分(其他線程)同時運行。線程是獨立的,因為它們都有單獨的執行路徑,這是在一個線程中發生異常的原因,它不會影響其他線程的執行。進程的所有線程共享公共內存。 **同時執行多個線程的過程稱為多線程。** 讓我們總結討論點: 1. 多線程的主要目的是同時執行程序的兩個或多個部分,以最大限度地利用 CPU 時間。多線程程序包含兩個或多個可以并發運行的部分。程序的每個這樣的部分都稱為線程。 2. 線程是輕量級子進程,它們共享公共內存空間。在多線程環境中,受益于多線程的程序利用最大 CPU 時間,以便將空閑時間保持在最小。 3. 線程可以處于以下狀態之一: `NEW` - 尚未啟動的線程處于此狀態。 `RUNNABLE` - 在 Java 虛擬機中執行的線程處于此狀態。 `BLOCKED` - 等待監視器鎖定被阻塞的線程處于此狀態。 `WAITING` - 一個無限期等待另一個線程執行特定操作的線程處于此狀態。 `TIMED_WAITING` - 正在等待另一個線程執行最多指定等待時間的操作的線程處于此狀態。 `TERMINATED` - 已退出的線程處于此狀態。 線程在給定時間點只能處于一種狀態。 **在此鏈接中了解有關線程狀態的更多信息**:[線程的生命周期](https://beginnersbook.com/2013/03/thread-life-cycle-in-java/) ## 多任務與多線程與多處理與并行處理 如果您是 java 新手,您可能會對這些術語感到困惑,因為在我們討論多線程時它們會被頻繁使用。我們簡要地談談它們。 **多任務處理:**能夠同時執行多個任務稱為多任務處理。 **多線程:**我們已經討論過了。這是一個同時執行多個線程的過程。多線程也稱為基于線程的多任務處理。 **多處理:**它與多任務處理相同,但在多處理中涉及多個 CPU。另一方面,一個 CPU 涉及多任務處理。 **并行處理:**它指的是在單個計算機系統中使用多個 CPU。 ## 用 Java 創建一個線程 在 Java 中創建線程有兩種方法: 1)通過擴展`Thread`類。 2)通過實現`Runnable`接口。 在開始創建線程的程序(代碼)之前,讓我們看一下`Thread`類的這些方法。我們在下面的示例中使用了很少的這些方法。 * `getName()`:用于獲取線程的名稱 * `getPriority()`:獲取線程的優先級 * `isAlive()`:確定線程是否仍在運行 * `join()`:等待線程終止 * `run()`:線程的入口點 * `sleep()`:暫停線程一段時間 * `start()`:通過調用`run()`方法啟動一個線程 ### 方法 1:通過擴展`Thread`類創建線程 **例 1:** ```java class MultithreadingDemo extends Thread{ public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ MultithreadingDemo obj=new MultithreadingDemo(); obj.start(); } } ``` **輸出:** ```java My thread is in running state. ``` **例 2:** ```java class Count extends Thread { Count() { super("my extending thread"); System.out.println("my thread created" + this); start(); } public void run() { try { for (int i=0 ;i<10;i++) { System.out.println("Printing the count " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("my thread interrupted"); } System.out.println("My thread run is over" ); } } class ExtendingExample { public static void main(String args[]) { Count cnt = new Count(); try { while(cnt.isAlive()) { System.out.println("Main thread will be alive till the child thread is live"); Thread.sleep(1500); } } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println("Main thread's run is over" ); } } ``` **輸出:** ```java my thread createdThread[my runnable thread,5,main] Main thread will be alive till the child thread is live Printing the count 0 Printing the count 1 Main thread will be alive till the child thread is live Printing the count 2 Main thread will be alive till the child thread is live Printing the count 3 Printing the count 4 Main thread will be alive till the child thread is live Printing the count 5 Main thread will be alive till the child thread is live Printing the count 6 Printing the count 7 Main thread will be alive till the child thread is live Printing the count 8 Main thread will be alive till the child thread is live Printing the count 9 mythread run is over Main thread run is over ``` ### 方法 2:通過實現`Runnable`接口創建線程 **一個簡單的例子** ```java class MultithreadingDemo implements Runnable{ public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ MultithreadingDemo obj=new MultithreadingDemo(); Thread tobj =new Thread(obj); tobj.start(); } } ``` **輸出:** ```java My thread is in running state. ``` **示例程序 2:** 觀察該程序的輸出并嘗試了解該程序中發生的情況。如果你已經理解了每個線程方法的用法,那么你應該不會遇到任何問題,理解這個例子。 ```java class Count implements Runnable { Thread mythread ; Count() { mythread = new Thread(this, "my runnable thread"); System.out.println("my thread created" + mythread); mythread.start(); } public void run() { try { for (int i=0 ;i<10;i++) { System.out.println("Printing the count " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("my thread interrupted"); } System.out.println("mythread run is over" ); } } class RunnableExample { public static void main(String args[]) { Count cnt = new Count(); try { while(cnt.mythread.isAlive()) { System.out.println("Main thread will be alive till the child thread is live"); Thread.sleep(1500); } } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } System.out.println("Main thread run is over" ); } } ``` **輸出:** ```java my thread createdThread[my runnable thread,5,main] Main thread will be alive till the child thread is live Printing the count 0 Printing the count 1 Main thread will be alive till the child thread is live Printing the count 2 Main thread will be alive till the child thread is live Printing the count 3 Printing the count 4 Main thread will be alive till the child thread is live Printing the count 5 Main thread will be alive till the child thread is live Printing the count 6 Printing the count 7 Main thread will be alive till the child thread is live Printing the count 8 Main thread will be alive till the child thread is live Printing the count 9 mythread run is over Main thread run is over ``` ## 線程優先級 * 線程優先級是整數,它決定了如何相對于其他線程處理一個線程。 * 線程優先級決定何時從一個正在運行的線程切換到另一個線程,該進程稱為上下文切換 * 線程可以自動釋放控制,并且準備運行的最高優先級線程被賦予 CPU。 * 無論優先級較低的線程正在做什么,線程都可以被更高優先級的線程搶占。每當一個更高優先級的線程想要運行它。 * 要設置線程的優先級`setPriority()`方法,這是類`Thread`類的方法。 * 我們可以使用`MIN_PRIORITY`,`NORM_PRIORITY`或`MAX_PRIORITY`代替以整數定義優先級。 ## 方法:`isAlive()`和`join()` * 在所有實際情況中,主線程應該最后完成其他從主線程產生的其他線程也將完成。 * 要知道線程是否已完成,我們可以在線程上調用`isAlive()`,如果線程未完成則返回`true`。 * 另一種通過使用`join()`方法實現此目的的方法,從父線程調用此方法使父線程等待直到子線程終止。 * 這些方法在`Thread`類中定義。 * 我們在上面的例子中也使用了`isAlive()`方法。 ## 同步 * 多線程為程序引入了異步行為。如果一個線程正在寫一些數據,那么另一個線程可能正在讀取相同的數據。這可能會帶來不一致。 * 當兩個或多個線程需要訪問共享資源時,應該有某種方式資源一次只能由一個資源使用。實現此目的的過程稱為同步。 * 要實現同步行為,java 具有同步方法。一旦線程在同步方法中,任何其他線程都不能在同一對象上調用任何其他同步方法。然后所有其他線程一直等到第一個線程從同步塊中出來。 * 當我們想要同步訪問不是為多線程訪問而設計的類的對象時,我們無法獲得需要同步訪問的方法的代碼,在這種情況下,我們無法將`synchronized`添加到適當的方法中。在 java 中我們有這個解決方案,以下列方式調用此類在同步塊內定義的方法(需要同步)。 ```java Synchronized(object) { // statement to be synchronized } ``` ## 線程間通信 我們有很少的方法可以讓 java 線程相互通信。這些方法是`wait()`,`notify()`,`notifyAll()`。所有這些方法只能在同步方法中調用。 1)了解同步 java 有一個監視器的概念。監視器可以被認為是一個只能容納一個線程的盒子。一旦線程進入監視器,所有其他線程必須等待該線程退出監視器。 2)`wait()`告訴調用線程放棄監視器并進入休眠狀態,直到某個其他線程進入同一個監視器并調用`notify()`。 3)`notify()`喚醒在同一個對象上調用`wait()`的第一個線程。 `notifyAll()`喚醒在同一個對象上調用`wait()`的所有線程。優先級最高的線程將首先運行。 **參考文獻** * Herbert Schildt 撰寫的 Java 2 完整參考
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看