首页> Java> java教程> 正文

Java 多线程面试题

WBOY
发布: 2024-08-30 16:29:25
原创
665 人浏览过

Java에서 멀티스레딩은 두 개 이상의 스레드를 동시에 실행하여 시스템 용량에 따라 프로세스 속도를 향상시키는 것을 포함합니다. 멀티스레딩은 가장 작은 단위를 동시에 처리하여 더 빠른 실행을 촉진합니다. 개발자는 이를 애니메이션, 게임, 대규모 애플리케이션 관리와 같은 작업에 사용하여 메모리 공간 및 시간 효율성에 기여합니다.

이제 Java Multithreading 관련 일자리를 찾고 있다면 Java Multithreading 면접 질문을 준비해야 합니다. 모든 면접은 실제로 직무 프로필에 따라 다릅니다. 여기서는 귀하의 인터뷰 성공에 도움이 될 중요한 Java 멀티스레딩 인터뷰 질문과 그에 대한 답변을 준비했습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

이 기사에서는 Java의 멀티스레딩 면접 질문에 관해 가장 중요하고 자주 묻는 질문 40가지를 소개합니다.

Q1. Thread의 다양한 상태를 설명하세요.

정답:
스레드의 상태를 스레드의 수명 주기라고도 합니다. 다음은 Thread의 다양한 상태입니다.

    • 신규:이는 스레드가 새로운 상태에 있고 시작 메소드를 호출하기 전에 스레드 클래스의 인스턴스를 생성해야 함을 의미합니다.
    • 실행 가능:시작 메소드를 호출한 후 스레드는 실행 가능 상태이고 스케줄러는 이를 실행 스레드로 선택하지 않았습니다.
    • 실행 중:스레드 스케줄러를 선택하면 실행 중인 상태입니다.
    • 차단됨: 실행 불가능이라고도 합니다. 스레드가 실행될 수 없는 경우 스레드는 여전히 살아 있습니다.
    • 종료됨:run 메소드를 종료하거나 데드 상태인 상태입니다.

Q2. Java의 스레드란 무엇인가요?

정답:스레드란 실행하는데 시간이 덜 걸리는 작은 단위를 말합니다. 이는 주로 실행 경로와 독립적입니다. 이는 시스템에서 사용 가능한 여러 CPU를 활용하는 방법 중 하나입니다. 다중 스레드의 도움으로 CPU 작업 프로세스가 더 빨라집니다. Java는 주로 멀티스레딩을 지원하는 데 사용됩니다. Java는 다중 프로세서를 활용하고 프로그램 성능을 향상시키기 위해 다중 스레딩을 지원합니다. Thread 클래스를 확장하거나 Runnable 인터페이스를 구현하는 것은 스레드를 생성하는 두 가지 방법입니다.

Q3. JAVA에서 스레드와 프로세스의 차이점을 설명하세요.

답변:스레드는 프로세스 내에서 실행되는 가장 작은 작업입니다. 프로세스는 둘 이상의 스레드 또는 여러 스레드가 있는 독립적인 실행 환경입니다. 스레드는 프로세스의 하위 부분입니다. 스레드는 프로세스의 데이터 세그먼트에 직접 액세스하는 반면 프로세스는 자체 데이터 세그먼트 복사본을 갖습니다. 스레드는 주로 프로세스가 생성한 주소를 공유하며, 프로세스는 자신의 주소를 가지고 있습니다.

스레드는 쉽게 생성할 수 있고, 프로세스 생성에는 할 일이 많이 필요합니다. 스레드는 다른 스레드와 쉽게 통신할 수 있는 반면, 프로세스는 자식 프로세스와 쉽게 통신할 수 있지만 프로세스 간 통신은 어렵습니다. 스레드는 자신의 스택을 가지고 있는 반면, 프로세스는 힙 메모리 등과 같은 메모리 자원을 공유합니다. 스레드에서 변경이 발생하면 모든 스레드에 영향을 주지만 프로세스에서는 다른 프로세스에 영향을 주지 않습니다.

Q4. Java 메모리 모델에 대해 설명해주세요.

답변:이것은 인터뷰에서 묻는 일반적인 Java 멀티스레딩 인터뷰 질문입니다. 현재 IT 산업에서 멀티스레딩 테스터는 일반적으로 몇 가지 책임을 수행해야 합니다.

Java 메모리 모델은 다양한 메모리 아키텍처, CPU 및 운영 체제 전반에 걸쳐 일관된 동작을 나타내기 위해 Java 프로그램이 준수해야 하는 특정 규칙 세트를 설정합니다. 이러한 규칙은 멀티스레딩에서 중요한 역할을 합니다. Java 메모리 모델은 스레드 중 하나에서 수행된 변경 사항을 구별하는 데 도움이 되며 해당 변경 사항은 다른 스레드에서도 볼 수 있어야 합니다. 이 모드는 프로그램 순서에서 모든 스레드가 나중에 오기 전에 각 스레드의 작업이 발생한다는 프로그램 순서입니다.

F5. Erklären Sie die Verwendung flüchtiger Variablen in Java Multithreading.

Antwort:Das Schlüsselwort oder die Variable volatile stellt sicher, dass gemeinsam genutzte Variablen oder Instanzvariablen ständig aktualisiert werden, wenn mehrere Threads Änderungen vornehmen. Es handelt sich um einen speziellen Modifikator, der nur auf Instanzvariablen anwendbar ist, nicht auf Methoden. Durch die Deklaration eines Felds als flüchtig in Java wird sichergestellt, dass das Java-Speichermodell konsistente Werte für diese Variable über alle Threads hinweg garantiert. Das Programm liest den Wert der flüchtigen Variablen immer aus dem Hauptspeicher und verringert so die Wahrscheinlichkeit von Speicherkonsistenzfehlern. Darüber hinaus kann eine flüchtige Java-Variable, die eine Objektreferenz darstellt, null sein. Die Anwendung des Schlüsselworts volatile ist erforderlich, wenn eine Variable über mehrere Threads hinweg verwendet wird.

Q6. Erklären Sie die Rennbedingung in Threads.

Antwort:Die Race-Bedingung tritt auf, wenn es einen Wettlauf zwischen mehreren Threads gibt. Diese Race-Bedingung wird hauptsächlich durch einige Programmierfehler oder -fehler verursacht. Der Thread, der ausgeführt werden muss, hat zunächst das Rennen verloren und dann den zweiten ausgeführt, und es kam zu einer Änderung im Verhalten des Codes, die als nicht deterministische Fehler bezeichnet wird. Aufgrund der zufälligen Natur der Threads wird es zu einem der schwierigsten Fehler, ihn herauszufinden und zu reproduzieren.

F7. Erklären Sie das Fork-Join-Framework in Java.

Antwort:Das Fork-Join-Framework wird in JDK7 eingeführt. Es ist ein leistungsstarkes Tool für Java-Entwickler, um die Vorteile mehrerer Prozessoren heutiger Weltserver zu nutzen. Es ist hauptsächlich für Arbeiten konzipiert, die in kleinere Teile unterteilt werden können. Das Hauptziel besteht darin, die verfügbare Rechenleistung zu nutzen, um die Anwendungsleistung zu steigern. Es wurde hauptsächlich der Work-Stealing-Algorithmus verwendet.

F8. Erklären Sie den Thread-Pool und seine Verwendung in Java.

Antwort:Der Thread-Pool wird als Thread-Pool bezeichnet. Der Thread wird im Allgemeinen als Arbeitsthread bezeichnet. Die Erstellung eines Threads ist in vielerlei Hinsicht kostspielig, sowohl zeit- als auch ressourcenintensiv. Wenn Sie den Thread zum Zeitpunkt der Prozessanforderung erstellen, verlangsamt dies im Allgemeinen die Antwortzeit des Prozessors und die Anzahl der Threads, die erstellt werden können, ist nur begrenzt begrenzt. Aufgrund dieser beiden Hauptprobleme wurde der Thread-Pool erstellt. In Java können wir mit der Java-API verschiedene Arten von Thread-Pools erstellen, z. B. einen einzelnen Thread-Pool, der jeweils nur einen Prozess ausführt. Der andere ist ein fester Thread-Pool, der eine feste Anzahl von Threads aufnimmt. Dann gibt es einen zwischengespeicherten Thread-Pool, einen erweiterbaren Thread-Pool, der hauptsächlich für viele Aufgaben geeignet ist.

F9. Wie können die Daten zwischen den Threads geteilt werden?

Antwort:Dies sind die beliebtesten Multithreading-Interviewfragen in Java, die in einem Interview gestellt werden. Einige beliebte Testfälle in der aktuellen IT-Branche.

Die Daten können mithilfe des gemeinsam genutzten Objekts oder einer gleichzeitigen Datenstruktur wie einer Blockierungswarteschlange zwischen Threads geteilt werden. Es folgt hauptsächlich dem Producer-Consumer-Muster und verwendet Warte- und Benachrichtigungsmethoden, die die gemeinsame Nutzung eines Objekts zwischen den beiden Threads beinhalten.

F10. Wie werden Threads im Stapel- und Heapspeicher verteilt?

Antwort:In Java verfügt jeder Thread über einen eigenen Stapel, der zum Speichern lokaler Variablen, Methodenparameter und Aufrufstapel verwendet wird. Heap-Speicher ist ein gemeinsamer Speicher, der von allen Threads gemeinsam genutzt wird.

F11. Unterscheiden Sie zwischen einem Thread und einem Prozess.

Antwort:

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 类的基础类,包含这些方法。语法如下:

雷雷

这意味着,如果你使用 wait(),你应该声明调用 wait() 的方法抛出此异常,或者捕获 InterruptedException。

Q13。用户线程和守护线程的区别?

答案:在 Java 中创建的线程称为用户线程。守护线程始终运行在后台,其完整的生命周期依赖于主线程。在后台运行的守护线程不会阻止 JVM 终止它。从守护线程创建的子线程也将是守护线程。

Q14。在 Java 中创建线程有哪些不同的方法?

答案:
Java中的线程可以通过两种方式创建:

  • 通过扩展 Thread 类
雷雷
  • 通过实现 Runnable 接口。
雷雷

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中文网其他相关文章!

相关标签:
来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!