Java에서 멀티스레딩은 두 개 이상의 스레드를 동시에 실행하여 시스템 용량에 따라 프로세스 속도를 향상시키는 것을 포함합니다. 멀티스레딩은 가장 작은 단위를 동시에 처리하여 더 빠른 실행을 촉진합니다. 개발자는 이를 애니메이션, 게임, 대규모 애플리케이션 관리와 같은 작업에 사용하여 메모리 공간 및 시간 효율성에 기여합니다.
이제 Java Multithreading 관련 일자리를 찾고 있다면 Java Multithreading 면접 질문을 준비해야 합니다. 모든 면접은 실제로 직무 프로필에 따라 다릅니다. 여기서는 귀하의 인터뷰 성공에 도움이 될 중요한 Java 멀티스레딩 인터뷰 질문과 그에 대한 답변을 준비했습니다.
무료 소프트웨어 개발 과정 시작
웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등
이 기사에서는 Java의 멀티스레딩 면접 질문에 관해 가장 중요하고 자주 묻는 질문 40가지를 소개합니다.
정답:
스레드의 상태를 스레드의 수명 주기라고도 합니다. 다음은 Thread의 다양한 상태입니다.
정답:스레드란 실행하는데 시간이 덜 걸리는 작은 단위를 말합니다. 이는 주로 실행 경로와 독립적입니다. 이는 시스템에서 사용 가능한 여러 CPU를 활용하는 방법 중 하나입니다. 다중 스레드의 도움으로 CPU 작업 프로세스가 더 빨라집니다. Java는 주로 멀티스레딩을 지원하는 데 사용됩니다. Java는 다중 프로세서를 활용하고 프로그램 성능을 향상시키기 위해 다중 스레딩을 지원합니다. Thread 클래스를 확장하거나 Runnable 인터페이스를 구현하는 것은 스레드를 생성하는 두 가지 방법입니다.
답변:스레드는 프로세스 내에서 실행되는 가장 작은 작업입니다. 프로세스는 둘 이상의 스레드 또는 여러 스레드가 있는 독립적인 실행 환경입니다. 스레드는 프로세스의 하위 부분입니다. 스레드는 프로세스의 데이터 세그먼트에 직접 액세스하는 반면 프로세스는 자체 데이터 세그먼트 복사본을 갖습니다. 스레드는 주로 프로세스가 생성한 주소를 공유하며, 프로세스는 자신의 주소를 가지고 있습니다.
스레드는 쉽게 생성할 수 있고, 프로세스 생성에는 할 일이 많이 필요합니다. 스레드는 다른 스레드와 쉽게 통신할 수 있는 반면, 프로세스는 자식 프로세스와 쉽게 통신할 수 있지만 프로세스 간 통신은 어렵습니다. 스레드는 자신의 스택을 가지고 있는 반면, 프로세스는 힙 메모리 등과 같은 메모리 자원을 공유합니다. 스레드에서 변경이 발생하면 모든 스레드에 영향을 주지만 프로세스에서는 다른 프로세스에 영향을 주지 않습니다.
답변:이것은 인터뷰에서 묻는 일반적인 Java 멀티스레딩 인터뷰 질문입니다. 현재 IT 산업에서 멀티스레딩 테스터는 일반적으로 몇 가지 책임을 수행해야 합니다.
Java 메모리 모델은 다양한 메모리 아키텍처, CPU 및 운영 체제 전반에 걸쳐 일관된 동작을 나타내기 위해 Java 프로그램이 준수해야 하는 특정 규칙 세트를 설정합니다. 이러한 규칙은 멀티스레딩에서 중요한 역할을 합니다. Java 메모리 모델은 스레드 중 하나에서 수행된 변경 사항을 구별하는 데 도움이 되며 해당 변경 사항은 다른 스레드에서도 볼 수 있어야 합니다. 이 모드는 프로그램 순서에서 모든 스레드가 나중에 오기 전에 각 스레드의 작업이 발생한다는 프로그램 순서입니다.
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.
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.
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.
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.
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.
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.
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. |
答案:Java使用notify()和notifyAll()方法配合wait()方法来实现同步和线程间通信。 Object 类是所有 Java 类的基础类,包含这些方法。语法如下:
雷雷这意味着,如果你使用 wait(),你应该声明调用 wait() 的方法抛出此异常,或者捕获 InterruptedException。
答案:在 Java 中创建的线程称为用户线程。守护线程始终运行在后台,其完整的生命周期依赖于主线程。在后台运行的守护线程不会阻止 JVM 终止它。从守护线程创建的子线程也将是守护线程。
答案:
Java中的线程可以通过两种方式创建:
答:面试中有常见的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中文网其他相关文章!