웹사이트 검색

Java 다중 스레딩 동시성 인터뷰 질문 및 답변


오늘은 Java Multithreading 인터뷰 질문과 답변을 살펴보겠습니다. 다중 스레딩과 동시성은 함께 진행되기 때문에 동시성 인터뷰 질문과 답변도 살펴볼 것입니다. 스레드는 자바 인터뷰 질문에서 인기 있는 주제 중 하나입니다. 여기서는 인터뷰 관점에서 가장 중요한 Java 멀티스레딩 인터뷰 질문을 나열하고 있지만 후속 질문을 처리하려면 Java 스레드에 대한 좋은 지식이 있어야 합니다.

Java 멀티스레딩 인터뷰 질문

  1. 프로세스와 스레드의 차이점은 무엇입니까?
  2. 멀티 스레드 프로그래밍의 이점은 무엇입니까?
  3. 사용자 스레드와 데몬 스레드의 차이점은 무엇입니까?
  4. 자바에서 어떻게 스레드를 만들 수 있나요?
  5. Thread 수명 주기의 다른 상태는 무엇입니까?
  6. Thread 클래스의 run() 메소드를 호출할 수 있습니까?
  7. 특정 시간 동안 스레드 실행을 어떻게 일시 중지할 수 있습니까?
  8. 스레드 우선순위에 대해 무엇을 이해하고 있습니까?
  9. 스레드 스케줄러 및 타임 슬라이싱이란 무엇입니까?
  10. 멀티 스레딩에서 컨텍스트 전환이란 무엇입니까?
  11. main()이 Java 프로그램에서 마지막 스레드인지 어떻게 확인할 수 있습니까?
  12. 스레드는 어떻게 서로 통신합니까?
  13. 스레드 통신 메서드 wait(), notify() 및 notifyAll()이 Object 클래스에 있는 이유는 무엇입니까?
  14. wait(), notify() 및 notifyAll() 메소드를 동기화된 메소드 또는 블록에서 호출해야 하는 이유는 무엇입니까?
  15. Thread sleep() 및 yield() 메소드가 정적인 이유는 무엇입니까?
  16. 자바에서 어떻게 스레드 안전성을 달성할 수 있습니까?
  17. 자바에서 휘발성 키워드란?
  18. 동기화 방법 또는 동기화 블록 중 어느 것이 더 선호됩니까?
  19. 자바에서 데몬 스레드를 만드는 방법
  20. ThreadLocal이란 무엇입니까?
  21. 스레드 그룹이란 무엇입니까? 왜 그것을 사용하지 않는 것이 좋습니까?
  22. Java 스레드 덤프란 무엇이며 어떻게 프로그램의 Java 스레드 덤프를 얻을 수 있습니까?
  23. 교착 상태란 무엇입니까? 교착 상태를 분석하고 피하는 방법은 무엇입니까?
  24. Java 타이머 클래스란 무엇입니까? 특정 간격 후에 실행되도록 작업을 예약하는 방법은 무엇입니까?
  25. 스레드 풀이란 무엇입니까? Java에서 스레드 풀을 어떻게 생성할 수 있습니까?
  26. Thread 클래스 run() 메서드를 재정의하지 않으면 어떻게 되나요?

Java 동시성 인터뷰 질문

  1. 원자적 작업이란 무엇입니까? Java Concurrency API의 원자 클래스는 무엇입니까?
  2. Java Concurrency API의 Lock 인터페이스는 무엇입니까? 동기화에 비해 어떤 이점이 있습니까?
  3. 집행자 프레임워크란 무엇입니까?
  4. BlockingQueue란 무엇입니까? Blocking Queue를 사용하여 Producer-Consumer 문제를 어떻게 구현할 수 있습니까?
  5. Callable 및 Future란 무엇입니까?
  6. FutureTask 클래스란 무엇입니까?
  7. 동시 수집 클래스란 무엇입니까?
  8. 실행자 클래스란 무엇입니까?
  9. Java 8에서 Concurrency API의 개선 사항은 무엇입니까?

Java 멀티스레딩 인터뷰 질문 및 답변

프로세스와 스레드의 차이점은 무엇입니까?\n프로세스는 자체 포함된 실행 환경이며 프로그램 또는 응용 프로그램으로 볼 수 있는 반면 스레드는 프로세스 내에서 실행되는 단일 작업입니다. Java 런타임 환경은 다양한 클래스와 프로그램을 프로세스로 포함하는 단일 프로세스로 실행됩니다. 스레드는 경량 프로세스라고 할 수 있습니다. 스레드는 생성하는 데 더 적은 리소스가 필요하고 프로세스에 존재하며 스레드는 프로세스 리소스를 공유합니다.\n\n\n다중 스레드 프로그래밍의 이점은 무엇입니까?\n다중 스레드 프로그래밍에서는 일부 스레드가 리소스를 얻기 위해 대기 중인 경우 CPU가 유휴 상태가 아니기 때문에 여러 스레드가 동시에 실행되어 성능이 향상됩니다. 여러 스레드가 힙 메모리를 공유하므로 여러 프로세스를 만드는 것보다 여러 스레드를 만들어 일부 작업을 실행하는 것이 좋습니다. 예를 들어 Servlet은 다중 스레드를 지원하지만 CGI는 지원하지 않기 때문에 Servlet이 CGI보다 성능이 더 좋습니다.\n\n\n사용자 스레드와 데몬 스레드의 차이점은 무엇입니까? Java 프로그램에서 스레드를 생성할 때 사용자 스레드라고 합니다. 데몬 스레드는 백그라운드에서 실행되며 JVM 종료를 막지 않습니다. 실행 중인 사용자 스레드가 없으면 JVM이 프로그램을 종료하고 종료합니다. 데몬 스레드에서 생성된 자식 스레드도 데몬 스레드입니다. Java에서 어떻게 스레드를 만들 수 있습니까? Java에서 Thread를 생성하는 방법에는 두 가지가 있습니다. 첫 번째는 Runnable 인터페이스를 구현한 다음 여기에서 Thread 객체를 생성하는 것이고 두 번째는 Thread 클래스를 확장하는 것입니다. Java에서 스레드를 생성하는 방법에 대해 자세히 알아보려면 이 게시물을 읽으십시오.\n\n\n스레드의 수명주기에서 다른 상태는 무엇입니까?

When we create a Thread in java program, its state is New. Then we start the thread that change it's state to Runnable. Thread Scheduler is responsible to allocate CPU to threads in Runnable thread pool and change their state to Running. Other Thread states are Waiting, Blocked and Dead. Read this post to learn more about [life cycle of thread](/community/tutorials/thread-life-cycle-in-java-thread-states-in-java).

Thread 클래스의 run() 메서드를 호출할 수 있습니까?

Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using **Thread.start()** method.

특정 시간 동안 스레드 실행을 어떻게 일시 중지할 수 있습니까?

We can use Thread class sleep() method to pause the execution of Thread for certain time. Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, it's state gets changed to runnable and based on thread scheduling, it gets executed.

스레드 우선순위에 대해 무엇을 이해하고 있습니까?

Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread but it doesn't guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an _int_ whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.

스레드 스케줄러 및 타임 슬라이싱이란 무엇입니까?

Thread Scheduler is the Operating System service that allocates the CPU time to the available runnable threads. Once we create and start a thread, it's execution depends on the implementation of Thread Scheduler. Time Slicing is the process to divide the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time. Thread scheduling can't be controlled by java, so it's always better to control it from application itself.

멀티스레딩에서 컨텍스트 스위칭이란 무엇입니까?

Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. Context Switching is the essential feature for multitasking operating system and support for multi-threaded environment.

Java 프로그램에서 main()이 마지막 스레드인지 어떻게 확인할 수 있습니까?

We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function. Here is an article about [Thread join method](/community/tutorials/java-thread-join-example).

스레드는 서로 어떻게 통신합니까?

When threads share resources, communication between Threads is important to coordinate their efforts. Object class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource. Check this post to learn more about [thread wait, notify and notifyAll](/community/tutorials/java-thread-wait-notify-and-notifyall-example).

스레드 통신 메서드 wait(), notify() 및 notifyAll()이 Object 클래스에 있는 이유는 무엇입니까?

In Java every Object has a monitor and wait, notify methods are used to wait for the Object monitor or to notify other threads that Object monitor is free now. There is no monitor on threads in java and synchronization can be used with any Object, that's why it's part of Object class so that every class in java has these essential methods for inter thread communication.

wait(), notify() 및 notifyAll() 메소드를 동기화된 메소드 또는 블록에서 호출해야 하는 이유는 무엇입니까?

When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object. Similarly when a thread calls notify() on any Object, it leaves the monitor on the Object and other waiting threads can get the monitor on the Object. Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block.

스레드 sleep() 및 yield() 메서드가 정적인 이유는 무엇입니까?

Thread sleep() and yield() methods work on the currently executing thread. So there is no point in invoking these methods on some other threads that are in wait state. That’s why these methods are made static so that when this method is called statically, it works on the current executing thread and avoid confusion to the programmers who might think that they can invoke these methods on some non-running threads.

Java에서 어떻게 스레드 안전성을 달성할 수 있습니까?

There are several ways to achieve thread safety in java - synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes. Learn more at [thread safety tutorial](/community/tutorials/thread-safety-in-java).

Java의 휘발성 키워드는 무엇입니까

When we use volatile keyword with a variable, all the threads read it's value directly from the memory and don't cache it. This makes sure that the value read is the same as in the memory.

동기화된 방법 또는 동기화된 블록 중 어느 것이 더 선호됩니까?

Synchronized block is more preferred way because it doesn't lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.

Java에서 데몬 스레드를 만드는 방법은 무엇입니까?

Thread class setDaemon(true) can be used to create daemon thread in java. We need to call this method before calling start() method else it will throw IllegalThreadStateException.

ThreadLocal이란 무엇입니까?

Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables. Every thread has its own ThreadLocal variable and they can use it gets () and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate the state with a thread. Check this post for small example program showing [ThreadLocal Example](/community/tutorials/java-threadlocal-example).

스레드 그룹이란 무엇입니까? 왜 그것을 사용하지 않는 것이 좋습니다?

ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesn't have any functionality that is not provided by Thread. It has two main features - to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has added _setUncaughtExceptionHandler(UncaughtExceptionHandler eh)_ method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore.

```
t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){

@Override
public void uncaughtException(Thread t, Throwable e) {
    System.out.println("exception occured:"+e.getMessage());
}
            
});
```

Java Thread Dump란 무엇이며 어떻게 프로그램의 Java Thread Dump를 얻을 수 있습니까?

A thread dump is a list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump - Using Profiler, Kill -3 command, jstack tool, etc. I prefer jstack tool to generate thread dump of a program because it's easy to use and comes with JDK installation. Since it's a terminal-based tool, we can create a script to generate thread dump at regular intervals to analyze it later on. Read this post to know more about [generating thread dump in java](/community/tutorials/java-thread-dump-visualvm-jstack-kill-3-jcmd).

교착 상태는 무엇입니까? 교착 상태를 분석하고 피하는 방법은 무엇입니까?

Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources. To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object. Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to [analyze deadlock in java](/community/tutorials/deadlock-in-java-example) with a sample program.

자바 타이머 클래스란? 지정된 간격 후에 실행되도록 작업을 예약하는 방법은 무엇입니까?

java.util.Timer is a utility class that can be used to schedule a thread to be executed at a certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals. java.util.TimerTask is an **[abstract class](/community/tutorials/abstract-class-in-java "Abstract Class in Java with Example")** that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class. Check this post for [java Timer example](/community/tutorials/java-timer-timertask-example).

스레드 풀이란 무엇입니까? Java에서 스레드 풀을 어떻게 만들 수 있습니까?

A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed. A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue. java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java. [Thread Pool Example](/community/tutorials/threadpoolexecutor-java-thread-pool-example-executorservice) program shows how to create and use Thread Pool in java. Or read [ScheduledThreadPoolExecutor Example](/community/tutorials/java-scheduler-scheduledexecutorservice-scheduledthreadpoolexecutor-example) to know how to schedule tasks after certain delay.

Thread 클래스의 run() 메서드를 재정의하지 않으면 어떻게 될까요?

Thread class run() method code is as shown below.

```
public void run() {
    if (target != null) {
        target.run();
    }
}
```

Above target set in the init() method of Thread class and if we create an instance of Thread class as `new TestThread()`, it's set to null. So nothing will happen if we don't override the run() method. Below is a simple example demonstrating this.

```
public class TestThread extends Thread {

	//not overriding Thread.run() method
	
	//main method, can be in other class too
	public static void main(String args[]){
		Thread t = new TestThread();
		System.out.println("Before starting thread");
		t.start();
		System.out.println("After starting thread");
	}
}
```

It will print only below output and terminate.

```
Before starting thread
After starting thread
```

Java 동시성 인터뷰 질문 및 답변

원자 연산이란 무엇입니까? Java Concurrency API의 원자 클래스는 무엇입니까? 원자성 작업은 다른 작업의 간섭 없이 단일 작업 단위에서 수행됩니다. 데이터 불일치를 피하기 위해 다중 스레드 환경에서 원자적 작업이 필요합니다. int++는 원자 연산이 아닙니다. 따라서 한 스레드가 해당 값을 읽고 1씩 증가할 때까지 다른 스레드는 잘못된 결과로 이어지는 이전 값을 읽었습니다. 이 문제를 해결하려면 카운트에 대한 증가 연산이 원자적임을 확인해야 합니다. 동기화를 사용하여 이를 수행할 수 있지만 Java 5 java.util.concurrent.atomic은 이를 원자적으로 달성하는 데 사용할 수 있는 int 및 long에 대한 래퍼 클래스를 제공합니다. 동기화를 사용하지 않고. 원자적 동시 클래스에 대해 자세히 알아보려면 이 문서로 이동하세요.\n\n\nJava Concurrency API의 Lock 인터페이스는 무엇입니까? 동기화에 비해 이점은 무엇입니까?\n잠금 인터페이스는 동기화된 메서드 및 문을 사용하여 얻을 수 있는 것보다 더 광범위한 잠금 작업을 제공합니다. 보다 유연한 구조화를 허용하고 상당히 다른 속성을 가질 수 있으며 여러 관련 Condition 개체를 지원할 수 있습니다. 자물쇠의 장점은 공정하게 만들 수 있습니다.\nLock 개체를 기다리는 동안 중단에 응답하는 스레드를 만들 수 있습니다.\n잠금을 획득하려고 시도할 수 있지만 잠금을 획득할 수 없는 경우 즉시 또는 시간 초과 후 반환\n다른 범위에서 다른 순서로 잠금을 획득하고 해제할 수 있습니다.\n\n자세한 내용은 Java 잠금 예를 참조하십시오.\n\n\n실행자 프레임워크란 무엇입니까?\nJava 5에서 Executor 프레임워크는 java.util.concurrent.Executor 인터페이스와 함께 도입되었습니다. Executor 프레임워크는 일련의 실행 정책에 따라 비동기 작업의 호출, 예약, 실행 및 제어를 표준화하기 위한 프레임워크입니다. 최대 임계값에 대한 제한 없이 많은 스레드를 생성하면 애플리케이션의 힙 메모리가 부족해질 수 있습니다. 따라서 한정된 수의 스레드를 풀링하고 재사용할 수 있으므로 ThreadPool을 만드는 것이 더 나은 솔루션입니다. 실행자 프레임워크는 Java에서 스레드 풀을 만드는 프로세스를 용이하게 합니다. Executors 프레임워크를 사용하여 스레드 풀을 생성하는 예제 코드를 배우려면 이 게시물을 확인하십시오.\n\n\nBlockingQueue란 무엇입니까? Blocking Queue를 사용하여 Producer-Consumer 문제를 어떻게 구현할 수 있습니까?\njava.util.concurrent.BlockingQueue는 요소를 검색 및 제거할 때 대기열이 비어 있지 않을 때까지 대기하고 요소를 추가할 때 대기열에서 공간이 사용 가능해질 때까지 기다리는 작업을 지원하는 대기열입니다. BlockingQueue는 null 값을 허용하지 않으며 대기열에 null 값을 저장하려고 하면 NullPointerException을 발생시킵니다. BlockingQueue 구현은 스레드로부터 안전합니다. 모든 큐잉 방법은 본질적으로 원자적이며 내부 잠금 또는 다른 형태의 동시성 제어를 사용합니다. BlockingQueue 인터페이스는 Java 컬렉션 프레임워크의 일부이며 주로 생산자-소비자 문제를 구현하는 데 사용됩니다. BlockingQueue를 사용한 생산자-소비자 문제 구현에 대해서는 이 게시물을 확인하십시오.\n\n\n호출 가능 및 미래는 무엇입니까?

Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception. The Callable interface uses Generics to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides the get() method that can wait for the Callable to finish and then return the result. Check this post for [Callable Future Example](/community/tutorials/java-callable-future-example).

FutureTask 클래스란?

FutureTask is the base implementation class of Future interface and we can use it with Executors for asynchronous processing. Most of the time we don't need to use FutureTask class but it comes real handy if we want to override some of the methods of Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to our requirements. Check out **[Java FutureTask Example](/community/tutorials/java-futuretask-example-program "Java FutureTask Example Program")** post to learn how to use it and what are different methods it has.

동시 컬렉션 클래스란 무엇입니까?

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates. Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn [how to avoid ConcurrentModificationException when using iterator](/community/tutorials/java-util-concurrentmodificationexception).

실행자 클래스란 무엇입니까?

Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes. Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.

Java 8에서 Concurrency API의 개선 사항은 무엇입니까?

Some important concurrent API enhancements are:

-   ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce() and search() methods.
-   CompletableFuture that may be explicitly completed (setting its value and status).
-   Executors newWorkStealingPool() method to create a work-stealing thread pool using all available processors as its target parallelism level.

**Recommended Read**: [Java 8 Features](/community/tutorials/java-8-features-with-examples "Java 8 Features for Developers – lambdas, Functional interface, Stream and Time API")

이것이 Java 스레드 및 동시성 인터뷰 질문의 전부입니다. 저는 이 목록에 더 많은 것을 추가했습니다. 따라서 나중에 참조할 수 있도록 게시물을 북마크하십시오.