> Java > java지도 시간 > 본문

Java의 멀티스레딩 인터뷰 질문

WBOY
풀어 주다: 2024-08-30 16:29:25
원래의
805명이 탐색했습니다.

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 메모리 모델은 스레드 중 하나에서 수행된 변경 사항을 구별하는 데 도움이 되며 해당 변경 사항은 다른 스레드에서도 볼 수 있어야 합니다. 이 모드는 프로그램 순서에서 모든 스레드가 나중에 오기 전에 각 스레드의 작업이 발생한다는 프로그램 순서입니다.

Q5. Java 멀티스레딩에서 휘발성 변수의 사용을 설명합니다.

답변: 휘발성 키워드나 변수는 여러 스레드가 변경될 때마다 공유 변수나 인스턴스 변수가 지속적으로 업데이트되도록 보장합니다. 메소드가 아닌 인스턴스 변수에만 적용되는 특수 수정자입니다. Java에서 필드를 휘발성으로 선언하면 Java 메모리 모델이 모든 스레드에서 해당 변수에 대해 일관된 값을 보장합니다. 프로그램은 항상 주 메모리에서 휘발성 변수의 값을 읽으므로 메모리 일관성 오류가 발생할 가능성이 줄어듭니다. 또한 객체 참조를 나타내는 Java 휘발성 변수는 null일 수 있습니다. 여러 스레드에서 변수를 사용하는 경우 휘발성 키워드 적용이 필요합니다.

Q6. 경쟁 조건을 스레드로 설명하세요.

정답: 경합 조건은 여러 스레드 간에 경합이 있을 때 발생합니다. 이 경쟁 조건은 주로 일부 프로그래밍 버그나 오류로 인해 발생합니다. 실행해야 하는 스레드는 처음에 경쟁에서 패한 다음 두 번째 실행 및 비결정적 버그라고 하는 코드 동작의 일부 변경을 실행했습니다. 스레드의 무작위 특성으로 인해 발견하고 재현하기 어려운 버그 중 하나가 됩니다.

Q7. Java의 포크 조인 프레임워크를 설명하세요.

답변: 포크 조인 프레임워크는 JDK7에 도입되었습니다. 이는 Java 개발자가 오늘날 세계 서버의 다중 프로세서를 활용할 수 있는 강력한 도구입니다. 주로 작은 조각으로 나눌 수 있는 작업을 위해 설계되었습니다. 주요 목표는 사용 가능한 처리 능력을 사용하여 애플리케이션 성능을 높이는 것입니다. 주로 작업훔치기 알고리즘을 사용했습니다.

Q8. 스레드 풀과 Java에서의 사용법을 설명하세요.

답변: 스레드 풀을 스레드 풀이라고 합니다. 스레드를 일반적으로 작업자 스레드라고 합니다. 스레드를 생성하는 데에는 시간과 리소스 등 많은 측면에서 비용이 많이 듭니다. 프로세스를 요청할 때 스레드를 생성하면 일반적으로 프로세서의 응답 시간이 느려지고 스레드 수에 일부 제한만 생성할 수 있습니다. 그래서 이 두 가지 큰 문제 때문에 스레드 풀이 만들어졌습니다. Java에서는 Java API를 사용하여 한 번에 하나의 프로세스만 사용하는 단일 스레드 풀과 같은 다양한 유형의 스레드 풀을 만들 수 있습니다. 다른 하나는 고정된 수의 스레드를 사용하는 고정 스레드 풀입니다. 그리고 캐시된 스레드 풀, 확장 가능한 스레드 풀이 있으며 주로 많은 작업에 적합합니다.

Q9. 스레드 간에 데이터를 어떻게 공유할 수 있나요?

답변: 이것은 인터뷰에서 가장 인기 있는 Java 멀티스레딩 인터뷰 질문입니다. 현재 IT 업계에서 인기 있는 테스트 사례입니다.

공유 객체나 Blocking Queue와 같은 동시 데이터 구조를 사용하여 스레드 간에 데이터를 공유할 수 있습니다. 주로 대기를 사용하는 생산자-소비자 패턴을 따르고 두 스레드 간에 객체를 공유하는 방법을 알려줍니다.

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는 wait() 메소드와 함께 inform() 및 informAll() 메소드를 사용하여 동기화 및 스레드 간 통신을 구현합니다. 모든 Java 클래스의 기본 클래스인 Object 클래스에는 이러한 메소드가 포함되어 있습니다. 아래에 주어진 구문 :

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를 생성하려면 Thread 클래스의 start() 메소드를 사용해야 합니다.

Q17. 특정 시간에 스레드 실행을 일시 중지할 수 있나요?

답변: 예, Java에서는 Thread 클래스의 sleep()을 호출하여 이를 수행할 수 있습니다. sleep () 메소드는 시간을 밀리초 단위로 나타내는 인수도 취합니다.

Q18. Java에서 스레드 예약을 어떻게 달성할 수 있나요?

답변: 예, Java에서 스레드 예약이 가능합니다. Java의 스레드는 시간 분할과 선점형 예약의 두 가지 방법으로 예약할 수 있습니다.

멀티스레딩에 관한 다음 Java 면접 질문으로 넘어가겠습니다.

Q19. 스레드를 두 번 시작할 수 있나요?

답변: 아니요, 스레드는 두 번 시작할 수 없습니다. 스레드를 두 번 시작하려고 하면 “java.lang.IllegalThreadStateException”이 발생합니다.

Q20. Java의 종료 후크란 무엇입니까?

답변: 이것은 인터뷰에서 가장 인기 있는 멀티스레딩 관련 Java 인터뷰 질문입니다. 종료 후크는 JVM이 정상적으로 또는 갑자기 종료될 때 리소스를 정리하는 데 사용되는 메커니즘입니다.

Q21. 휘발성이란 무엇입니까?

정답: Volatile은 Java의 키워드로, 변수와 함께 사용할 수 있습니다. 변수가 휘발성으로 선언되면 모든 스레드는 캐시가 아닌 주 메모리에서 동일한 변수의 값을 읽습니다. 따라서 여러 스레드가 작업에서 동일한 변수를 사용할 때 오류 읽기를 방지합니다.

Q22. JAVA에서는 스레드를 어떻게 구현하나요?

답변: Java는 프로그램에서 스레드를 구현하는 두 가지 방법을 제공합니다. 인터페이스 java.Lang.Runnable에는 인스턴스를 통해 실행하는 작업이 필요한 Java.lang.A 행의 인스턴스가 있습니다. Thread 클래스는 이미 Runnable을 구현하므로 사용자는 Thread 클래스를 확장하거나 Runnable 인터페이스를 구현하여 run() 메서드를 직접 재정의할 수 있습니다.

Q23. Java에서 언제 Runnable을 사용하고 언제 Thread를 사용합니까?

답변: Java는 단일 상속만 허용하므로 Thread 클래스를 확장하는 것보다 Runnable 인터페이스를 구현하는 것이 더 좋습니다. 클래스는 여러 인터페이스를 구현할 수 있지만 하나의 클래스만 확장할 수 있으므로 클래스 간에 코드를 공유할 때 더 큰 유연성을 제공합니다.

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 학습자의 빠른 성장을 도와주세요!