在Java中,多線程涉及同時執行兩個或多個線程,根據系統容量提高處理速度。多執行緒同時處理最小的單元,有利於更快的執行。開發人員將其用於動畫、遊戲和管理大型應用程式等任務,有助於提高記憶體空間和時間效率。
現在,如果您正在尋找與 Java 多執行緒相關的工作,您需要準備 Java 多執行緒面試問題。根據職位簡介,每次面試確實有所不同。在這裡,我們準備了重要的 Java 多線程面試問題及其答案,這將幫助您在面試中取得成功。
開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
本文將介紹 40 個關於 Java 多執行緒面試問題的最重要和最常見的問題。
答案:
執行緒的狀態也稱為執行緒的生命週期。以下是 Thread 的不同狀態:
答案:執行緒是指執行時間較短的小單元。它主要與執行路徑無關。這是利用機器中可用的多個 CPU 的方法之一。在多執行緒的幫助下,CPU任務的處理變得更快。 Java主要用於提供多執行緒的支援。 Java 支援多執行緒以利用多個處理器並提高程式效能。擴展 Thread 類別或實作 Runnable 介面是建立執行緒的兩種方法。
答案:執行緒是進程內執行的最小任務。進程是一種獨立的執行環境,具有多個執行緒或多個執行緒。執行緒是進程的細分。執行緒可以直接存取進程的資料段,而進程則擁有自己的資料段副本。執行緒主要共享進程創建的位址,進程有自己的位址。
執行緒可以輕鬆創建,進程創建需要做很多事情。執行緒可以很容易地與其他執行緒通信,而進程可以很容易地與子進程通信,但進程間通訊很困難。執行緒有自己的堆疊,而進程共享堆記憶體等記憶體資源。如果線程中發生任何更改,都會影響所有線程,但在進程中,不會影響其他進程。
答案:這些是面試中常見的 Java 多執行緒面試問題。在目前的 IT 產業中,多執行緒測試人員通常需要承擔多項職責。
Java 記憶體模型建立了一組特定的規則,Java 程式必須遵守這些規則,以便在各種記憶體架構、CPU 和作業系統中表現出一致的行為。這些規則在多線程中起著至關重要的作用。 Java 記憶體模型有助於區分在其中一個執行緒中所做的更改,而該更改也應該對其他執行緒可見。這個 mod 是一個程式順序,它表示每個執行緒的操作發生在程式順序中較晚的每個執行緒之前。
答案:volatile 關鍵字或變數可確保每當多個執行緒進行變更時,共享變數或實例變數都會收到持續更新。它是一個特殊的修飾符,僅適用於實例變量,不適用於方法。在 Java 中將欄位宣告為 volatile 可確保 Java 記憶體模型保證該變數在所有執行緒中的值一致。程式總是從主記憶體中讀取易失性變數的值,從而減少記憶體一致性錯誤的可能性。此外,表示物件引用的 Java 易失性變數可以為 null。當一個變數在多個執行緒中使用時,需要使用 volatile 關鍵字。
答案:當多個執行緒之間存在競爭時,就會出現競爭條件。這種競爭條件主要是由於一些程式錯誤或錯誤所引起的。最初需要執行的線程在競爭中失敗,然後執行第二個線程,並且程式碼行為發生一些變化,稱為非確定性錯誤。由於線程的隨機性,它成為難以發現和重現的錯誤之一。
答案:fork-join框架是在JDK7中引入的。它是 Java 開發人員利用當今世界伺服器的多個處理器的強大工具。它主要是為可以分成較小部分的工作而設計的。主要目標是利用可用的處理能力來提高應用程式效能。它主要使用了工作竊取演算法。
答案:執行緒池稱為執行緒池。該執行緒通常稱為工作執行緒。從許多方面來說,創建線程的成本很高,例如時間和資源。當您在請求進程時建立線程,通常會減慢處理器的回應時間,並且只能建立一些線程數量限制。所以,因為這兩大問題,所以創建了一個線程池。在Java中,Java API允許我們建立不同類型的執行緒池,就像單一執行緒池一樣,一次只需要一個程序。另一種是固定執行緒池,佔用固定數量的執行緒。然後是一個快取線程池,一個可擴展的線程池,主要適合很多任務。
答案:這些是面試中最受歡迎的 Java 多執行緒面試問題。目前IT行業中一些流行的測試案例。
借助共享物件或並發資料結構(如阻塞佇列),可以在執行緒之間共用資料。它主要遵循生產者-消費者模式,使用等待並通知涉及在兩個執行緒之間共享物件的方法。
答案:在Java中,每個執行緒都有自己的堆疊,用於儲存局部變數、方法參數和呼叫堆疊。堆記憶體是所有線程共享的公共記憶體。
答案:
Feature | Process | Thread |
Definition | An autonomous program running. | A process’s lightweight unit. |
Execution | Operates on its own. | Operates within a process’s framework. |
Communication | Requires communication between processes. | Communication made easier and data space shared. |
Synchronization | More remote and possibly requiring more overhead. | Requires shared data synchronization mechanisms. |
Resource Overhead | Greater (differing memory spaces). | Lower (shares the process’s resources). |
Creation Time | Slower and requiring more resources. | Quicker and with less overhead needed. |
Fault Tolerance | More resilient. | Failure could impact the entire process if it is not as strong. |
答案:Java使用notify()和notifyAll()方法來配合wait()方法來實現同步和執行緒間通訊。 Object 類別是所有 Java 類別的基礎類,包含這些方法。文法如下:
public final void wait() throws InterruptedException
這意味著,如果你使用 wait(),你應該聲明呼叫 wait() 的方法拋出此異常,或捕獲 InterruptedException。
答案:在 Java 中建立的執行緒稱為使用者執行緒。守護線程始終運行在後台,其完整的生命週期依賴於主線程。在背景運行的守護線程不會阻止 JVM 終止它。從守護線程建立的子線程也將是守護線程。
答案:
Java中的執行緒可以透過兩種方式建立:
class MyThread extends Thread { public void run() { // Code to be executed in the new thread } } // Creating and starting the thread MyThread myThread = new MyThread(); myThread.start();
class MyRunnable implements Runnable { public void run() { // Code to be executed in the new thread } } // Creating a thread using the Runnable interface Thread myThread = new Thread(new MyRunnable()); myThread.start();
答:面試中有常見的Java面試問題,問到多執行緒。以下是線程的生命週期:
答案:直接呼叫run()方法會成功編譯並執行程序,但同一個程式不會被視為Thread,因為不會建立新的呼叫堆疊,程式會啟動它的在主程式運行的同一呼叫堆疊中執行。
要建立一個應使用新呼叫堆疊運行的線程,必須使用 Thread 類別的 start () 方法。
答:是的,在Java中可以透過呼叫Thread類別的sleep()來實現。 sleep() 方法也接受一個參數,該參數指示以毫秒為單位的時間。
答案:是的,Java 中的執行緒調度是可能的。 Java中的執行緒調度有兩種方式,即時間分片和搶佔式調度。
讓我們進入下一個關於多執行緒的 Java 面試問題。
答案:不,一個執行緒不能啟動兩次。如果我們嘗試啟動一個執行緒兩次,它將拋出「java.lang.IllegalThreadStateException」。
答案:這些是面試中最常見的關於多執行緒的 Java 面試問題。 shutdown hook 是一種用於在 JVM 正常或突然關閉時清理資源的機制。
答案:Volatile是java中的關鍵字,它可以與變數一起使用。如果一個變數被宣告為 volatile,那麼所有執行緒都會從主記憶體而不是從快取中讀取同一個變數的值;因此,當多個執行緒在其操作中使用相同變數時,它可以防止錯誤讀取。
答案:Java 提供了兩種在程式中實作執行緒的方法。介面 java.Lang.Runnable 有一個 Java.lang.A 實例,需要透過實例執行任務的一行。 Thread 類別已經實作了 Runnable,因此使用者可以透過擴展 Thread 類別或實作 Runnable 介面來直接重寫 run() 方法。
答案:Java 提供了更好的實作 Runnable 介面而不是擴展 Thread 類,因為 Java 只允許單一繼承。由於一個類可以實現多個接口,但只能擴展一個類,因此在類之間共享代碼時,這提供了更大的靈活性。
答案:原因是執行緒調度程式負責處理執行緒的執行。調度程式可以在 Windows、UNIX 和 LINUX 平台上執行不同的效能。執行時,同一個執行緒在不同平台上可能會給予不同的輸出,有時甚至在同一平台上。為了解決這個問題,使用者可以建立相同的 Runnable 對象,在兩個執行緒中建立 run() 迴圈並同時啟動這兩行。
Answer: Java facilitates users to share variables present in different threads. A volatile variable acts as a unique modifier that can be used only for instance variables. It provides that a write will happen before any consequent read. The Java memory model ensures the consistency of this variable.
Answer: The synchronized keyword is used when the goal is to allow only one thread to run at a time in a specific section of code. It can be applied to define four different types of blocks, as shown below:
It can be declared as follows:
Public synchronized void example () {}
A volatile variable will never land up in a deadlock as it does not require obtaining any lock. While in synchronized variables, it may end up in a draw if they are not done correctly.
Answer: Object class has monitors that allow the Thread to lock an object, while Thread does not have any monitors. The object class’s monitor checks for the thing to see if it is available. Thread class having these methods would not help as multiple threads exist on an object, not vice versa.
Answer:
Answer: In Java, multithreading, one cannot force start a thread. Only thread schedulers can control lines and are not exposed to any API for control.
Answer: A thread in the sleep() method does not leave the lock and moves to the waiting state. The Thread waits for sleep time to get over.
Answer :
When it comes to software development, multithreading has several benefits:
Answer:
1. Preemptive Scheduling: It is a scheduling technique used by operating systems that allows the system to start or stop a task that is presently underway in order to focus on a higher priority task.
Example: In a preemptive scheduling system, even if a lower-priority task is presently running, it may be preempted from execution if a higher-priority task becomes ready to run.
2. Round Robin Scheduling (Time Slicing): It is a scheduling technique where each process or thread is assigned a fixed time slot or quantum during which it can execute. Once the time slice expires, the next task in the queue is given CPU time.
For instance, if the time slice is set to 10 milliseconds and there are three tasks (A, B, and C), each task receives 10 milliseconds of CPU time in a cyclic fashion (A for 10 ms, then B for 10 ms, and so on).
Answer: Every thread in a system that is waiting for a resource that another waiting thread is holding causes a deadlock. In this case, all of the threads are in a universal waiting state because none of them can continue executing. A deadlock occurs when there is no opportunity for any thread to execute, leading to a halt. Complex circumstances known as deadlocks can impair a program’s regular runtime and possibly lead to coding problems. Maintaining the system’s performance and stability requires controlling and avoiding deadlocks.
Answer: Tools that display blocked threads, such as thread dumps, can be used to identify deadlocks. TryLock with timeouts, acquiring locks in a consistent order, and reducing lock contention are ways to prevent deadlocks. To lower the chance of deadlocks, properly design multithreaded programs and make use of higher-level concurrency tools.
Answer: Yes, every thread in multithreaded programming has a separate stack. Local variables and details about each thread’s function calls are kept on the stack. Each thread will function independently and have a dedicated area to manage its execution context because of this division.
Answer: A class is considered thread-safe when multiple threads can use its methods or objects concurrently without experiencing conflicts. In multithreaded programming, achieving thread safety is essential to avoiding race situations. This can be done in a few different ways:
Answer:
Characteristic | User Threads |
Daemon Threads |
Creation and Control | created and managed by the user or the application. | The application or user creates and controls these threads, but they can be explicitly set as daemon threads using the setDaemon(true) method. |
JVM Termination Impact | JVM will wait for user threads to complete before exiting. | JVM can exit even if daemon threads are still running. Daemon threads are abruptly stopped if all user threads have finished their execution. |
Example (Java) |
java Thread userThread = new Thread(() -> { /* Thread logic */ }); userThread.start(); 登入後複製 |
java Thread daemonThread = new Thread(() -> { /* Thread logic */ }); daemonThread.setDaemon(true); daemonThread.start(); 登入後複製 |
Answer: The Thread class in Java provides the setDaemon(boolean on) method, which can be used to create daemon threads. When all non-daemon threads have finished running, a daemon thread operates in the background and does not stop the Java Virtual Machine (JVM) from shutting down.
Here’s an easy illustration:
public class DaemonThreadExample { public static void main(String[] args) { Thread daemonThread = new Thread(() -> { while (true) { // Do some background tasks System.out.println("Daemon Thread is running"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); // Setting the thread as daemon daemonThread.setDaemon(true); // Starting the daemon thread daemonThread.start(); // Main thread System.out.println("Main thread is finished"); } }
Output:
Explanation:
The daemonThread.setDaemon(true) line in this example designates the thread as a daemon thread. Regardless of its state, the daemon thread will end when the main thread completes its execution and the JVM terminates.
It is crucial to remember that a thread will throw an IllegalThreadStateException if it is not started as a daemon. You are unable to alter a thread’s daemon status once it has begun.
Answer:
1. notify():
2. notifyAll():
Answer: Multiple processes create a deadlock in computing when they become stuck holding resources, waiting for another process to acquire that resource. This situation prevents any progress and results in mutual blocking between the processes.
When the following four requirements referred to as the Coffman conditions—are satisfied, a deadlock usually results:
以上是Java 多執行緒面試題的詳細內容。更多資訊請關注PHP中文網其他相關文章!