Java でのマルチスレッド面接の質問

WBOY
リリース: 2024-08-30 16:29:25
オリジナル
805 人が閲覧しました

Java では、マルチスレッドには 2 つ以上のスレッドの同時実行が含まれ、システム容量に基づいて処理速度が向上します。マルチスレッドでは最小単位が同時に処理されるため、実行が高速化されます。開発者はアニメーション、ゲーム、大規模なアプリケーションの管理などのタスクにこれを使用し、メモリ空間と時間の効率化に貢献します。

Java でのマルチスレッド化に関連する仕事を探している場合は、Java でのマルチスレッド化の面接の質問に備える必要があります。実際、すべての面接は職務プロフィールに基づいて異なります。ここでは、面接での成功に役立つ、Java でのマルチスレッド面接の重要な質問とその回答を用意しました。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

この記事では、Java でのマルチスレッド面接の質問に関して最も重要でよくある質問 40 個を紹介します。

Q1.スレッドのさまざまな状態について説明します。

答え:
スレッドの状態は、スレッドのライフサイクルとも呼ばれます。以下はスレッドのさまざまな状態です:

    • New: スレッドが新しい状態にあり、start メソッドを呼び出す前にスレッド クラスのインスタンスを作成する必要があることを意味します。
    • 実行可能: start メソッドを呼び出した後、スレッドは実行可能な状態ですが、スケジューラーはスレッドを実行中のスレッドとして選択していません。
    • 実行中: スレッド スケジューラが選択されると、実行状態になります。
    • ブロック済み: 実行不可とも呼ばれます。スレッドが実行できない場合でも、スレッドは生きています。
    • 終了: これは、run メソッドを終了したとき、またはデッド状態にあるときの状態です。

Q2. Java のスレッドとは何ですか?

答え: スレッドとは、実行にかかる時間が短い小さな単位を指します。これは主に実行パスから独立しています。これは、マシンで利用可能な複数の CPU を活用する方法の 1 つです。マルチスレッドの助けにより、CPU タスクの処理が高速化されます。 Java は主に、マルチスレッドのサポートを提供するために使用されます。 Java は、複数のプロセッサを利用してプログラムのパフォーマンスを向上させるマルチスレッドをサポートしています。スレッドを作成するには、Thread クラスを拡張するか、Runnable インターフェイスを実装する 2 つの方法があります。

Q3. JAVAのスレッドとプロセスの違いを説明します。

答え: スレッドは、プロセス内で実行される最小のタスクです。このプロセスは、複数のスレッドを備えた自己完結型の実行環境です。スレッドはプロセスを細分化したものです。スレッドはプロセスのデータ セグメントに直接アクセスできますが、プロセスはデータ セグメントの独自のコピーを持っています。スレッドは主にプロセスによって作成されたアドレスを共有し、プロセスは独自のアドレスを持ちます。

スレッドは簡単に作成できますが、プロセスの作成には多くの作業が必要です。スレッドは他のスレッドと簡単に通信でき、プロセスは子プロセスと簡単に通信できますが、プロセス間通信は困難です。スレッドには独自のスタックがありますが、プロセスはヒープ メモリなどのメモリ リソースを共有します。スレッド内で変更が行われた場合、すべてのスレッドに影響しますが、プロセス内では他のプロセスには影響しません。

Q4. Java メモリ モデルについて説明します。

答え: これらは、面接で尋ねられる Java でのマルチスレッド面接の一般的な質問です。現在の IT 業界では、通常、マルチスレッド テスターがいくつかの責任を負う必要があります。

Java メモリ モデルは、さまざまなメモリ アーキテクチャ、CPU、オペレーティング システムにわたって一貫した動作を示すために、Java プログラムが従う必要がある特定のルール セットを確立します。これらのルールは、マルチスレッド化において重要な役割を果たします。Java メモリ モデルは、スレッドの 1 つで行われた変更を区別するのに役立ち、その変更は他のスレッドにも表示される必要があります。この MOD は、各スレッドのアクションがプログラム順序の後ろに来るすべてのスレッドより前に発生するというプログラム順序です。

Q5. Java マルチスレッドでの Volatile 変数の使用について説明します。

答え: volatile キーワードまたは変数により、複数のスレッドが変更を行うたびに、共有変数またはインスタンス変数が常に更新されるようになります。これは、メソッドではなくインスタンス変数にのみ適用できる特別な修飾子です。 Java でフィールドを volatile として宣言すると、Java メモリ モデルがすべてのスレッドにわたってその変数の一貫した値を保証します。プログラムは常にメイン メモリから volatile 変数の値を読み取るため、メモリ整合性エラーが発生する可能性が低くなります。さらに、オブジェクト参照を表す Java 揮発性変数は null になる可能性があります。変数が複数のスレッド間で使用される場合は、 volatile キーワードを適用する必要があります。

Q6.競合状態についてスレッドで説明します。

答え: 競合状態は、複数のスレッド間で競合が発生すると発生します。この競合状態は主に、プログラミングのバグやエラーが原因で発生します。実行する必要があるスレッドは、最初は競争に負け、次に 2 番目のスレッドを実行し、非決定性バグと呼ばれるコードの動作に何らかの変更を加えました。スレッドのランダムな性質により、これは発見して再現するのが難しいバグの 1 つとなります。

Q7. Java のフォーク結合フレームワークについて説明します。

答え: フォークジョイン フレームワークは JDK7 で導入されました。これは、Java 開発者が今日の世界中のサーバーの複数のプロセッサを活用するための強力なツールです。主に、より小さな部分に分割できる作業用に設計されています。主な目標は、利用可能な処理能力を利用してアプリケーションのパフォーマンスを向上させることです。主に仕事盗用アルゴリズムが使用されました。

Q8.スレッド プールと Java でのその使用法について説明します。

答え: スレッドのプールはスレッド プールとして知られています。このスレッドは一般にワーカースレッドと呼ばれます。スレッドの作成には、時間やリソースなど、多くの点でコストがかかります。処理要求時にスレッドを作成すると、一般にプロセッサの応答時間が遅くなり、作成できるスレッド数も制限されます。したがって、これら 2 つの大きな問題のため、スレッド プールが作成されました。 Java では、Java API を使用して、一度に 1 つのプロセスのみを実行する単一スレッド プールなど、さまざまなタイプのスレッド プールを作成できます。もう 1 つは、固定数のスレッドを使用する固定スレッド プールです。さらに、キャッシュされたスレッド プール、拡張可能なスレッド プールがあり、主に多くのタスクに適しています。

Q9.スレッド間でデータを共有するにはどうすればよいですか?

答え: これらは、面接で尋ねられる Java のマルチスレッド面接の質問の中で最も人気のあるものです。現在の IT 業界で人気のあるテスト ケースをいくつか紹介します。

共有オブジェクトまたはブロッキング キューのような同時データ構造を使用して、データをスレッド間で共有できます。これは主に、wait を使用してプロデューサーとコンシューマーのパターンに従い、2 つのスレッド間でオブジェクトを共有することを伴うメソッドを通知します。

Q10.スレッドはスタック メモリとヒープ メモリにどのように分散されますか?

答え: 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() メソッドと組み合わせて使用​​し、同期とスレッド間通信を実装します。すべての Java クラスの基本クラスである Object クラスには、これらのメソッドが含まれています。構文は以下のとおりです:

public final void wait() throws InterruptedException
ログイン後にコピー

これは、wait() を使用する場合、wait() を呼び出すメソッドがこの例外をスローすることを宣言するか、InterruptedException をキャッチする必要があることを意味します。

Q13.ユーザースレッドとデーモンスレッドを区別しますか?

答え: Java で作成されたスレッドはユーザー スレッドと呼ばれます。デーモン スレッドは常にバックグラウンドで実行され、その完全なライフサイクルはメイン スレッドに依存します。バックグラウンドで実行されているデーモン スレッドは、JVM によるデーモン スレッドの終了を妨げません。デーモンスレッドから作成された子スレッドもデーモンスレッドになります。

Q14. Java でスレッドを作成するさまざまな方法は何ですか?

答え:
Java のスレッドは 2 つの方法で作成できます:

  • 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 Interface を実装することによって。
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 のスレッドのライフサイクルは何ですか?

答え: Java の面接では、マルチスレッドに関するよくある質問が聞かれます。以下はスレッドのライフサイクルです:

Java でのマルチスレッド面接の質問

  • 新規
  • 実行可能です。
  • 実行中です。
  • ブロックされました。
  • 終了しました。

Q16. Thread クラスの run() メソッドを呼び出すとどうなりますか?

答え: run() メソッドを直接呼び出すと、プログラムは正常にコンパイルされて実行されますが、新しい呼び出しスタックは作成されず、プログラムはスレッドとして扱われないため、同じプログラムはスレッドとして扱われません。メインが実行されているのと同じコールスタックで実行されます。

新しい呼び出しスタックで実行するスレッドを作成するには、Thread クラスの start () メソッドを使用する必要があります。

Q17.特定の時間にスレッドの実行を一時停止できますか?

答え: はい、これは Java で Thread クラスの sleep () を呼び出すことで実現できます。 sleep () メソッドは、時間をミリ秒単位で示す引数も受け取ります。

Q18. Java でスレッドのスケジューリングを実現するにはどうすればよいですか?

答え: はい、Java でのスレッド スケジューリングは可能です。 Java のスレッドは、タイム スライシングとプリエンプティブ スケジューリングという 2 つの方法でスケジュールできます。

次の Java インタビューのマルチスレッドに関する質問に移りましょう。

Q19.スレッドは 2 回開始できますか?

答え: いいえ、スレッドを 2 回開始することはできません。スレッドを 2 回開始しようとすると、「java.lang.IllegalThreadStateException」がスローされます。

Q20. Java のシャットダウン フックとは何ですか?

答え: これらは、面接で尋ねられるマルチスレッドに関する Java 面接の質問で最も人気のあるものです。シャットダウン フックは、JVM が通常または突然シャットダウンしたときにリソースをクリーンアップするために使用されるメカニズムです。

Q21.揮発性とは何ですか?

答え: Volatile は Java のキーワードであり、変数とともに使用できます。変数が volatile として宣言されている場合、すべてのスレッドは同じ変数の値をキャッシュではなくメイン メモリから読み取ります。したがって、複数のスレッドが操作で同じ変数を使用する場合の読み取りエラーを防ぎます。

Q22. JAVA でスレッドを実装するにはどうすればよいですか?

答え: Java には、プログラムにスレッドを実装する 2 つの方法があります。インターフェース java.Lang.Runnable には、インスタンスを介してタスクを実行する必要がある Java.lang.A 行のインスタンスがあります。 Thread クラスは既に Runnable を実装しているため、ユーザーは Thread クラスを拡張するか、Runnable インターフェイスを実装することで run() メソッドを直接オーバーライドできます。

Q23. Java で Runnable を使用する場合と Thread を使用する場合は何ですか?

答え: Java では単一継承しか許可されていないため、Thread クラスを拡張するよりも Runnable インターフェイスを実装する方が適切です。クラスは複数のインターフェイスを実装できますが、拡張できるのは 1 つのクラスだけであるため、クラス間でコードを共有する際の柔軟性が高まります。

Q24. スレッドの動作は予測できないと言われるのはなぜですか?

答え: この理由は、スレッドの実行を処理するスレッド スケジューラにあります。スケジューラは、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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!