首頁 >Java >java教程 >Java 多執行緒面試題

Java 多執行緒面試題

WBOY
WBOY原創
2024-08-30 16:29:25883瀏覽

在Java中,多線程涉及同時執行兩個或多個線程,根據系統容量提高處理速度。多執行緒同時處理最小的單元,有利於更快的執行。開發人員將其用於動畫、遊戲和管理大型應用程式等任務,有助於提高記憶體空間和時間效率。

現在,如果您正在尋找與 Java 多執行緒相關的工作,您需要準備 Java 多執行緒面試問題。根據職位簡介,每次面試確實有所不同。在這裡,我們準備了重要的 Java 多線程面試問題及其答案,這將幫助您在面試中取得成功。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

本文將介紹 40 個關於 Java 多執行緒面試問題的最重要和最常見的問題。

Q1。解釋Thread的不同狀態。

答案:
執行緒的狀態也稱為執行緒的生命週期。以下是 Thread 的不同狀態:

    • New:表示執行緒處於新建狀態,需要在呼叫start方法之前建立執行緒類別的實例。
    • Runnable:呼叫start方法後,執行緒處於可運行狀態,調度器尚未選擇其為運行執行緒。
    • 運行中:當選擇執行緒調度器時,它處於運作狀態。
    • 阻塞:也稱為不可運作。當線程沒有資格運行時,它仍然存活。
    • Termied:這是退出run方法或處於dead狀態時的狀態。

Q2。 Java中的執行緒是什麼?

答案:執行緒是指執行時間較短的小單元。它主要與執行路徑無關。這是利用機器中可用的多個 CPU 的方法之一。在多執行緒的幫助下,CPU任務的處理變得更快。 Java主要用於提供多執行緒的支援。 Java 支援多執行緒以利用多個處理器並提高程式效能。擴展 Thread 類別或實作 Runnable 介面是建立執行緒的兩種方法。

Q3。解釋一下JAVA中線程和進程的區別。

答案:執行緒是進程內執行的最小任務。進程是一種獨立的執行環境,具有多個執行緒或多個執行緒。執行緒是進程的細分。執行緒可以直接存取進程的資料段,而進程則擁有自己的資料段副本。執行緒主要共享進程創建的位址,進程有自己的位址。

執行緒可以輕鬆創建,進程創建需要做很多事情。執行緒可以很容易地與其他執行緒通信,而進程可以很容易地與子進程通信,但進程間通訊很困難。執行緒有自己的堆疊,而進程共享堆記憶體等記憶體資源。如果線程中發生任何更改,都會影響所有線程,但在進程中,不會影響其他進程。

第四季。解釋一下Java記憶體模型。

答案:這些是面試中常見的 Java 多執行緒面試問題。在目前的 IT 產業中,多執行緒測試人員通常需要承擔多項職責。

Java 記憶體模型建立了一組特定的規則,Java 程式必須遵守這些規則,以便在各種記憶體架構、CPU 和作業系統中表現出一致的行為。這些規則在多線程中起著至關重要的作用。 Java 記憶體模型有助於區分在其中一個執行緒中所做的更改,而該更改也應該對其他執行緒可見。這個 mod 是一個程式順序,它表示每個執行緒的操作發生在程式順序中較晚的每個執行緒之前。

Q5。講解Java多執行緒中Volatile變數的使用。

答案:volatile 關鍵字或變數可確保每當多個執行緒進行變更時,共享變數或實例變數都會收到持續更新。它是一個特殊的修飾符,僅適用於實例變量,不適用於方法。在 Java 中將欄位宣告為 volatile 可確保 Java 記憶體模型保證該變數在所有執行緒中的值一致。程式總是從主記憶體中讀取易失性變數的值,從而減少記憶體一致性錯誤的可能性。此外,表示物件引用的 Java 易失性變數可以為 null。當一個變數在多個執行緒中使用時,需要使用 volatile 關鍵字。

Q6。解釋線程中的競爭條件。

答案:當多個執行緒之間存在競爭時,就會出現競爭條件。這種競爭條件主要是由於一些程式錯誤或錯誤所引起的。最初需要執行的線程在競爭中失敗,然後執行第二個線程,並且程式碼行為發生一些變化,稱為非確定性錯誤。由於線程的隨機性,它成為難以發現和重現的錯誤之一。

Q7。解釋一下Java中的fork-join框架。

答案:fork-join框架是在JDK7中引入的。它是 Java 開發人員利用當今世界伺服器的多個處理器的強大工具。它主要是為可以分成較小部分的工作而設計的。主要目標是利用可用的處理能力來提高應用程式效能。它主要使用了工作竊取演算法。

Q8。講解Java中的執行緒池及其使用。

答案:執行緒池稱為執行緒池。該執行緒通常稱為工作執行緒。從許多方面來說,創建線程的成本很高,例如時間和資源。當您在請求進程時建立線程,通常會減慢處理器的回應時間,並且只能建立一些線程數量限制。所以,因為這兩大問題,所以創建了一個線程池。在Java中,Java API允許我們建立不同類型的執行緒池,就像單一執行緒池一樣,一次只需要一個程序。另一種是固定執行緒池,佔用固定數量的執行緒。然後是一個快取線程池,一個可擴展的線程池,主要適合很多任務。

Q9。執行緒之間如何共享資料?

答案:這些是面試中最受歡迎的 Java 多執行緒面試問題。目前IT行業中一些流行的測試案例。

借助共享物件或並發資料結構(如阻塞佇列),可以在執行緒之間共用資料。它主要遵循生產者-消費者模式,使用等待並通知涉及在兩個執行緒之間共享物件的方法。

問題10。執行緒在棧記憶體和堆記憶體中是如何分佈的?

答案:在Java中,每個執行緒都有自己的堆疊,用於儲存局部變數、方法參數和呼叫堆疊。堆記憶體是所有線程共享的公共記憶體。

Q11。區分執行緒和進程。

答案:

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.

Q12。 Java wait() 方法有什麼用?

答案:Java使用notify()和notifyAll()方法來配合wait()方法來實現同步和執行緒間通訊。 Object 類別是所有 Java 類別的基礎類,包含這些方法。文法如下:

public final void wait() throws InterruptedException

這意味著,如果你使用 wait(),你應該聲明呼叫 wait() 的方法拋出此異常,或捕獲 InterruptedException。

Q13。使用者線程和守護線程的差別?

答案:在 Java 中建立的執行緒稱為使用者執行緒。守護線程始終運行在後台,其完整的生命週期依賴於主線程。在背景運行的守護線程不會阻止 JVM 終止它。從守護線程建立的子線程也將是守護線程。

Q14。在 Java 中建立執行緒有哪些不同的方法?

答案:
Java中的執行緒可以透過兩種方式建立:

  • 透過擴充 Thread 類別
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();
  • 透過實作 Runnable 介面。
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();

Q15。 JAVA中Thread的生命週期是怎麼樣的?

答:面試中有常見的Java面試問題,問到多執行緒。以下是線程的生命週期:

Java 多執行緒面試題

  • 可運行。
  • 跑步。
  • 已屏蔽。
  • 已終止。

Q16。如果我們呼叫 Thread 類別的 run() 方法會發生什麼事?

答案:直接呼叫run()方法會成功編譯並執行程序,但同一個程式不會被視為Thread,因為不會建立新的呼叫堆疊,程式會啟動它的在主程式運行的同一呼叫堆疊中執行。

要建立一個應使用新呼叫堆疊運行的線程,必須使用 Thread 類別的 start () 方法。

Q17。我們可以在特定時間暫停線程的執行嗎?

答:是的,在Java中可以透過呼叫Thread類別的sleep()來實現。 sleep() 方法也接受一個參數,該參數指示以毫秒為單位的時間。

Q18。 Java中如何實作執行緒的調度?

答案:是的,Java 中的執行緒調度是可能的。 Java中的執行緒調度有兩種方式,即時間分片和搶佔式調度。

讓我們進入下一個關於多執行緒的 Java 面試問題。

Q19。一個執行緒可以啟動兩次嗎?

答案:不,一個執行緒不能啟動兩次。如果我們嘗試啟動一個執行緒兩次,它將拋出「java.lang.IllegalThreadStateException」。

Q20。 Java 中的關閉鉤子是什麼?

答案:這些是面試中最常見的關於多執行緒的 Java 面試問題。 shutdown hook 是一種用於在 JVM 正常或突然關閉時清理資源的機制。

Q21。什麼是揮發性的?

答案:Volatile是java中的關鍵字,它可以與變數一起使用。如果一個變數被宣告為 volatile,那麼所有執行緒都會從主記憶體而不是從快取中讀取同一個變數的值;因此,當多個執行緒在其操作中使用相同變數時,它可以防止錯誤讀取。

Q22。 JAVA中如何實現線程?

答案:Java 提供了兩種在程式中實作執行緒的方法。介面 java.Lang.Runnable 有一個 Java.lang.A 實例,需要透過實例執行任務的一行。 Thread 類別已經實作了 Runnable,因此使用者可以透過擴展 Thread 類別或實作 Runnable 介面來直接重寫 run() 方法。

Q23。 Java中什麼時候使用Runnable,什麼時候使用Thread?

答案:Java 提供了更好的實作 Runnable 介面而不是擴展 Thread 類,因為 Java 只允許單一繼承。由於一個類可以實現多個接口,但只能擴展一個類,因此在類之間共享代碼時,這提供了更大的靈活性。

Q24。 為什麼說Thread的行為是無法預測的?

答案:原因是執行緒調度程式負責處理執行緒的執行。調度程式可以在 Windows、UNIX 和 LINUX 平台上執行不同的效能。執行時,同一個執行緒在不同平台上可能會給予不同的輸出,有時甚至在同一平台上。為了解決這個問題,使用者可以建立相同的 Runnable 對象,在兩個執行緒中建立 run() 迴圈並同時啟動這兩行。

Q25. What is a volatile variable in Java, and what is its significance?

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.

Q26. What is the use of the synchronized keyword? What is the difference between synchronized and volatile keywords?

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:

  • Instance methods
  • Static methods
  • Code blocks inside instance methods
  • Code blocks inside static methods

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.

Q27. Why methods like wait(), notify(), and notify all() are present in the object class and not in the Thread class?

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.

Q28. Explain the difference between sleep() and wait() methods.

Answer:

  • When the wait() method is called, the monitor moves the Thread from running to waiting for the state. Once a thread is in wait(), then it can move to runnable only when it has notified () or told all () for that object. The scheduler changes the state after this. While in the sleep() method, the state is changed to wait and will return to runnable only after sleep time.
  • The wait () method is a part of Java.lang.Object class, while sleep() is a part of Java.lang.Thread class.

Q29. How to force start a thread in Java?

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.

Q30. Does Thread leave object lock when wait() and sleep() methods are called?

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.

Q31. Explain the advantages of Multithreading.

Answer :
When it comes to software development, multithreading has several benefits:

  1. Enhanced Performance: By utilizing multiple processor cores to execute tasks in parallel, multithreading improves the overall performance of applications.
  2. Responsiveness: Multithreading helps applications with graphical user interfaces stay responsive by running background tasks simultaneously.
  3. Resource Utilization: By allowing some threads to continue processing while others wait for I/O operations, efficient use of the system’s resources is achieved, maximizing the use of CPU and I/O devices.
  4. Maintainability and modularity: Multithreading encourages modular design by assigning distinct threads to handle different functions, which results in code that is easier to read and maintain.
  5. Asynchronous Programming: Multithreading makes it possible for tasks to run independently of the main program flow, which is essential for managing events or asynchronous input/output tasks.

Q32. How does time slicing differ from preemptive scheduling?

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).

Q33. What is deadlock?

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.

Java 多執行緒面試題

Q34. How can a deadlock situation be identified? How is it easily avoidable?

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.

Q35. Is there a stack for every thread in multithreaded programming?

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.

Q36. How is a thread’s safety achieved?

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:

  • Synchronization: Limiting access to shared resources by employing locks and other mechanisms to make sure that only one thread at a time can access crucial areas.
  • Volatile Keyword: Designating variables as volatile ensures consistency by making changes made to the variable by one thread visible to other threads.
  • Lock-Based Mechanism: This technique uses explicit locks, like ReentrantLock, to control access to important code segments and stop thread interference.
  • Atomic wrapper classes: (such as AtomicInteger and AtomicBoolean) for operations that must be carried out atomically without the need for explicit.

Q37. Tell me the difference between User thread and Daemon thread?

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();

Q38. How are daemon threads made?

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:
Java 多執行緒面試題

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.

Q39. How do notify() and notifyAll() differ from one another?

Answer:
1. notify():

Java 多執行緒面試題

  • Wakes up one of the threads that are currently waiting on the object.
  • The scheduling policy of the JVM determines which thread will be notified, and this decision is not guaranteed.

2. notifyAll():

Java 多執行緒面試題

  • Wakes up all the threads that are currently waiting on the object.
  • Usually makes sure that every thread in line has an opportunity to obtain the lock and verify the altered state.

Q40. What does it mean to be in a deadlock and when can it happen?

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:

  • Mutual Exclusion: One or more resources must be kept in a non-sharable mode, which limits the resource’s use to a single process at a time.
  • Hold and Wait: A process needs to be holding one resource at a time while it waits to obtain more resources that other processes are holding.
  • No Preemption: Resources must be released willingly from a process; they cannot be taken away by force.
  • Circular Wait: When two or more processes are in a circular chain, each process is waiting for a resource that the subsequent process in the chain is holding.

以上是Java 多執行緒面試題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn