你好,我是 shengjk1,多年大廠經驗,努力構建 通俗易懂的、好玩的編程語言教程。 歡迎關注!你會有如下收益:
- 了解大廠經驗
- 擁有和大廠相匹配的技術等
希望看什么,評論或者私信告訴我!
文章目錄
- 一、前言
- 二 線程
- 2.1 進程和線程關系
- 2.2 為什么需要線程
- 2.3 線程的狀態
- 2.4 如何創建線程
- 2.5 線程停止
- 2.5.1 使用標識
- 2.5.2 使用 interrup()
- 三、總結
一、前言
線程算是相對較高級的內容,主要的原因不是說他難,而是它不可見。最近基于多線程的方式優化了一些 FLink 程序,所以這一系列,我們聊聊多線程
二 線程
2.1 進程和線程關系
進程是計算機系統進行資源分配和調度的最小單位,換句話說我們平時雙擊那些后綴為 .exe的文件時都會產生一個進程。
進程可以產生若干個線程,是程序執行的最小單位,換句話說,進程就是房子,線程就是房子內一個個干活的人
2.2 為什么需要線程
線程在計算機編程中扮演著重要角色,其重要性主要體現在以下幾個方面:
- 提高程序響應性:通過多線程處理,程序可以變得更加靈活和響應更加及時。在一個單線程程序中,如果有一個耗時的操作,會導致整個程序阻塞,影響用戶體驗;而多線程可以使程序保持活躍,允許其他線程繼續執行,從而提高程序的響應性。
- 提高程序性能:多線程可以充分利用多核處理器的優勢,實現并發執行多個任務,加快程序運行速度,提高系統整體性能。通過并行執行,程序可以更有效地利用計算資源,加快任務完成的速度。
- 實現并發處理:多線程允許程序同時執行多個任務,這對于需要同時處理多個事件或任務的應用程序至關重要。例如,在服務器端應用中,多線程可以同時處理多個客戶端請求。
- 資源共享:多個線程可以共享進程的資源,如內存空間、文件句柄等,這種資源共享有助于簡化程序設計,并提高效率。不同線程之間可以相互通信、共享數據,協同工作來完成復雜任務。
- 實現復雜邏輯:有些程序需要同時進行多項任務,通過多線程可以更好地組織和管理復雜的邏輯,提高程序的可維護性和可拓展性。
- 實現異步編程:多線程可以實現異步操作和事件驅動,允許程序在等待某些操作完成時繼續執行其他操作,提高程序的效率和靈活性。異步編程模型通過非阻塞方式進行任務處理,可以有效提升程序的吞吐量和性能。 綜合以上原因,線程在計算機編程中是不可或缺的,它提供了一種有效的機制來實現并發處理、提高程序的響應性和性能、實現資源共享以及管理復雜的程序邏輯。因此,了解和靈活運用線程是提升程序效率和優化系統性能的重要手段。
2.3 線程的狀態
public enum State {/*** Thread state for a thread which has not yet started.*/NEW,/*** Thread state for a runnable thread. A thread in the runnable* state is executing in the Java virtual machine but it may* be waiting for other resources from the operating system* such as processor.*/RUNNABLE,/*** Thread state for a thread blocked waiting for a monitor lock.* A thread in the blocked state is waiting for a monitor lock* to enter a synchronized block/method or* reenter a synchronized block/method after calling* {@link Object#wait() Object.wait}.*/BLOCKED,/*** Thread state for a waiting thread.* A thread is in the waiting state due to calling one of the* following methods:* <ul>* <li>{@link Object#wait() Object.wait} with no timeout</li>* <li>{@link #join() Thread.join} with no timeout</li>* <li>{@link LockSupport#park() LockSupport.park}</li>* </ul>** <p>A thread in the waiting state is waiting for another thread to* perform a particular action.** For example, a thread that has called <tt>Object.wait()</tt>* on an object is waiting for another thread to call* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on* that object. A thread that has called <tt>Thread.join()</tt>* is waiting for a specified thread to terminate.*/WAITING,/*** Thread state for a waiting thread with a specified waiting time.* A thread is in the timed waiting state due to calling one of* the following methods with a specified positive waiting time:* <ul>* <li>{@link #sleep Thread.sleep}</li>* <li>{@link Object#wait(long) Object.wait} with timeout</li>* <li>{@link #join(long) Thread.join} with timeout</li>* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>* </ul>*/TIMED_WAITING,/*** Thread state for a terminated thread.* The thread has completed execution.*/TERMINATED;
}
2.4 如何創建線程
Thread thread = new Thread();
thread.start();
在Java中,當調用線程對象的start()
方法時,實際上是調用了start0()
方法,該方法會啟動一個新的本地操作系統線程,
然后調用Java中的run()
方法來執行線程的任務。所有 線程的主要工作的方法就是 run 方法,那么怎么樣來豐富 run 方法的內容呢?
首先通過匿名內部類來啟動線程,如:
Thread thread1 = new Thread(){@Overridepublic void run() {while (true){if (Thread.currentThread().isInterrupted()){System.out.println("Interruted!");break;}Thread.yield();try {TimeUnit.SECONDS.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("thread1==");}}
} ;thread1.start();
當然也可以實現 Runnable 接口來實現線程的功能
public class CreateThread3 implements Runnable {public static void main(String[] args) {Thread t1 = new Thread(new CreateThread3());t1.start();}@Overridepublic void run() {System.out.println("Oh,I am Runnable");}}
2.5 線程停止
2.5.1 使用標識
public class ControlledThread extends Thread {private volatile boolean shouldStop = false;public void stopThread() {shouldStop = true;}@Overridepublic void run() {while (!shouldStop) {// 線程執行的任務System.out.println("Thread is running...");}System.out.println("Thread stopped.");}public static void main(String[] args) {ControlledThread thread = new ControlledThread();thread.start();// 模擬停止線程try {Thread.sleep(3000); // 等待3秒} catch (InterruptedException e) {e.printStackTrace();}thread.stopThread();}
}
需要注意的是,這里使用 volatile 變量來保證該變量對于任意線程可見,如果不用 volatile 的話,則線程可能會無法停止
2.5.2 使用 interrup()
public class InterruptedThread extends Thread {@Overridepublic void run() {while (!Thread.interrupted()) {// 線程執行的任務System.out.println("Thread is running...");}System.out.println("Thread stopped.");}public static void main(String[] args) {InterruptedThread thread = new InterruptedThread();thread.start();// 模擬停止線程try {Thread.sleep(3000); // 等待3秒thread.interrupt(); // 中斷線程} catch (InterruptedException e) {e.printStackTrace();}}
}
三、總結
文章圍繞多線程的核心概念和應用展開,通過具體Java代碼示例,深入講解了線程的創建、狀態管理以及線程停止的方法。作者強調了線程在優化程序性能和響應性方面的重要性,鼓勵讀者深入了解并靈活運用多線程編程技術