logo

Java 멀티스레딩 및 동시성 인터뷰 질문

멀티스레딩과 동기화는 자바 프로그래밍의 전형적인 장으로 간주됩니다. 게임 개발사에서는 멀티스레딩 관련 면접 질문을 주로 많이 하십니다. 자주 묻는 Java 멀티스레딩 및 동시성 인터뷰 질문 목록은 다음과 같습니다.


멀티스레딩 인터뷰 질문

1) 멀티스레딩이란 무엇입니까?

멀티스레딩은 여러 스레드를 동시에 실행하는 프로세스입니다. 멀티스레딩은 멀티태스킹을 달성하는 데 사용됩니다. 메모리를 덜 소모하고 빠르고 효율적인 성능을 제공합니다. 주요 장점은 다음과 같습니다.

  • 스레드는 동일한 주소 공간을 공유합니다.
  • 실은 가볍습니다.
  • 프로세스 간 통신 비용이 저렴합니다.
자세한 내용은.

2) 스레드란 무엇인가?

스레드는 가벼운 하위 프로세스입니다. 각 스레드가 다른 스택 프레임에서 실행되기 때문에 이는 별도의 실행 경로입니다. 프로세스에는 여러 스레드가 포함될 수 있습니다. 스레드는 프로세스 리소스를 공유하지만 여전히 독립적으로 실행됩니다.

자세한 내용은.

3) 프로세스와 스레드를 구별합니까?

프로세스와 스레드에는 다음과 같은 차이점이 있습니다.

  • 실행 중인 프로그램을 프로세스라고 합니다. 스레드는 프로세스의 하위 집합입니다.
  • 프로세스는 독립적인 반면 스레드는 프로세스의 하위 집합입니다.
  • 프로세스는 메모리에서 서로 다른 주소 공간을 갖고 있는 반면 스레드는 공유 주소 공간을 포함합니다.
  • 프로세스에 비해 스레드 간 컨텍스트 전환이 더 빠릅니다.
  • 프로세스 간 통신은 스레드 간 통신보다 느리고 비용이 많이 듭니다.
  • 상위 프로세스의 변경 사항은 하위 프로세스에 영향을 미치지 않지만 상위 스레드의 변경 사항은 하위 스레드에 영향을 줄 수 있습니다.

4) 스레드 간 통신을 통해 무엇을 이해합니까?

  • 동기화된 스레드 간의 통신 프로세스를 스레드 간 통신이라고 합니다.
  • 스레드 간 통신은 Java에서 스레드 폴링을 방지하는 데 사용됩니다.
  • 스레드는 임계 섹션에서 실행을 일시 중지하고 다른 스레드는 실행될 동일한 임계 섹션에 진입(또는 잠금)할 수 있습니다.
  • wait(), inform() 및 informAll() 메소드를 통해 얻을 수 있습니다.

5) Java에서 wait() 메소드의 목적은 무엇입니까?

wait() 메소드는 Java의 Object 클래스에서 제공됩니다. 이 방법은 Java에서 스레드 간 통신에 사용됩니다. java.lang.Object.wait()는 현재 스레드를 일시 중지하고 다른 스레드가 inform() 또는 informAll() 메서드를 호출하지 않을 때까지 기다리는 데 사용됩니다. 구문은 아래와 같습니다.

공개 최종 무효 대기()


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

wait 메서드를 호출해야 합니다. 그렇지 않으면 오류가 발생합니다. java.lang.IllegalMonitorStateException 예외. 또한, inform(), informAll()과의 스레드간 통신을 위해서는 wait() 메소드가 필요하다. 따라서 적절하고 정확한 통신을 위해서는 동기화된 블록에 존재해야 합니다.


7) 멀티스레딩의 장점은 무엇입니까?

멀티스레딩 프로그래밍에는 다음과 같은 장점이 있습니다.

  • 멀티스레딩을 사용하면 애플리케이션/프로그램이 이미 일부 백그라운드 작업으로 실행 중이더라도 항상 입력에 반응할 수 있습니다.
  • 멀티스레딩을 사용하면 스레드가 독립적으로 실행되므로 작업 실행 속도가 빨라집니다.
  • 멀티스레딩은 스레드가 공통 메모리 리소스를 공유하므로 캐시 메모리 활용도를 향상시킵니다.
  • 멀티스레딩은 하나의 서버가 동시에 여러 스레드를 실행할 수 있으므로 필요한 서버 수를 줄입니다.

8) 스레드 수명주기의 상태는 무엇입니까?

스레드는 수명 동안 다음 상태 중 하나를 가질 수 있습니다.

    새로운:이 상태에서는 new 연산자를 사용하여 Thread 클래스 객체가 생성되지만 스레드는 살아 있지 않습니다. 스레드는 start() 메서드를 호출할 때까지 시작되지 않습니다.실행 가능:이 상태에서는 start() 메서드를 호출한 후 스레드를 실행할 준비가 됩니다. 그러나 스레드 스케줄러는 스레드를 아직 선택하지 않았습니다.달리기:이 상태에서 스레드 스케줄러는 준비 상태에서 스레드를 선택하고 스레드가 실행 중입니다.대기 중/차단됨:이 상태에서는 스레드가 실행 중이 아니지만 여전히 살아 있거나 다른 스레드가 완료되기를 기다리고 있습니다.사망/종료됨:run() 메서드가 종료되면 스레드는 종료되거나 작동 불능 상태가 됩니다.

9) 선점형 스케줄링과 타임 슬라이싱의 차이점은 무엇입니까?

선점형 스케줄링에서는 우선 순위가 가장 높은 작업이 대기 또는 데드 상태로 들어가거나 우선 순위가 더 높은 작업이 나타날 때까지 실행됩니다. 시간 분할에서는 미리 정의된 시간 동안 작업이 실행된 다음 준비된 작업 풀에 다시 들어갑니다. 그런 다음 스케줄러는 우선 순위 및 기타 요소에 따라 다음에 실행할 작업을 결정합니다.


10) 컨텍스트 스위칭이란 무엇입니까?

컨텍스트 전환에서는 프로세스(또는 스레드)의 상태를 저장하여 나중에 동일한 지점에서 복원하고 실행을 재개할 수 있습니다. 컨텍스트 전환을 통해 여러 프로세스가 동일한 CPU를 공유할 수 있습니다.


11) Thread 생성을 위해 Thread 클래스와 Runnable 인터페이스를 구별합니까?

스레드는 두 가지 방법을 사용하여 생성할 수 있습니다.

  • Thread 클래스를 확장하여
  • Runnable 인터페이스를 구현함으로써

그러나 두 방법의 주요 차이점은 다음과 같습니다.

  • Thread 클래스를 확장하면 다른 클래스를 확장할 수 없습니다. Java는 Runnable 인터페이스를 구현하는 동안 다중 상속을 허용하지 않기 때문입니다. (필요하다면) 다른 기본 클래스를 확장할 수도 있습니다.
  • Thread 클래스를 확장함으로써 각 스레드는 고유한 개체를 생성하고 Runnable 인터페이스를 구현하는 동안 해당 개체와 연결됩니다. 여러 스레드가 동일한 객체를 공유합니다.
  • Thread 클래스는 getPriority(), isAlive 등과 같은 다양한 내장 메소드를 제공하는 반면 Runnable 인터페이스는 run()과 같은 단일 메소드를 제공합니다.

12) Join() 메소드는 무엇입니까?

Join() 메소드는 스레드가 죽을 때까지 기다립니다. 즉, 현재 실행 중인 스레드가 조인된 스레드가 작업을 완료할 때까지 실행을 중지합니다. Join 메소드는 다음과 같은 방법으로 Thread 클래스에 오버로드됩니다.

  • public void Join()이 InterruptedException을 발생시킵니다.
  • 공개 무효 조인(긴 밀리초)으로 인해 InterruptedException이 발생합니다.
자세한 내용은.

13) sleep() 메소드의 목적과 작동을 설명하십시오.

Java의 sleep() 메소드는 특정 시간 동안 스레드를 차단하는 데 사용됩니다. 이는 특정 시간 동안 스레드의 실행을 일시 중지한다는 의미입니다. 그렇게 하는 방법에는 두 가지가 있습니다.

통사론:

자바스크립트로 자다
  • public static void sleep(긴 밀리초)으로 인해 InterruptedException이 발생합니다.
  • public static void sleep(long milliseconds, int nanos)이 InterruptedException을 발생시킵니다.

sleep() 메소드 작동

sleep() 메소드를 호출하면 주어진 시간 동안 현재 스레드의 실행을 일시 중지하고 다른 스레드(사용 가능한 경우)에 우선 순위를 부여합니다. 또한 대기 시간이 완료되면 다시 이전 스레드가 상태를 대기에서 실행 가능으로 변경하고 실행 상태가 되며 전체 프로세스는 실행이 완료되지 않을 때까지 계속 작동합니다.


14) wait() 메소드와 sleep() 메소드의 차이점은 무엇입니까?

기다리다()잠()
1) wait() 메소드는 Object 클래스에 정의되어 있습니다.sleep() 메소드는 Thread 클래스에 정의되어 있습니다.
2) wait() 메소드는 잠금을 해제합니다.sleep() 메서드는 잠금을 해제하지 않습니다.

15) 스레드를 두 번 시작할 수 있습니까?

아니요, 스레드를 다시 시작할 수 없습니다. 스레드가 시작되고 실행되면 Dead 상태가 되기 때문입니다. 따라서 스레드를 두 번 시작하려고 하면 RuntimeException 'java.lang.IllegalThreadStateException'이 발생합니다. 다음 예를 고려하십시오.

 public class Multithread1 extends Thread { public void run() { try { System.out.println('thread is executing now........'); } catch(Exception e) { } } public static void main (String[] args) { Multithread1 m1= new Multithread1(); m1.start(); m1.start(); } } 

산출

 thread is executing now........ Exception in thread 'main' java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:708) at Multithread1.main(Multithread1.java:13) 
자세한 내용은.

16) start() 대신 run() 메소드를 호출할 수 있나요?

예, run() 메소드를 직접 호출하는 것은 유효하지만 스레드로 작동하지 않고 대신 일반 객체로 작동합니다. 스레드 간에는 컨텍스트 전환이 발생하지 않습니다. start() 메서드를 호출하면 내부적으로 run() 메서드가 호출됩니다. 이 메서드는 스레드에 대한 새 스택을 생성하지만 run()을 직접 호출하면 새 스택이 생성되지 않습니다.

문자 비교 자바
자세한 내용은.

17) 데몬 스레드는 어떻습니까?

데몬 스레드는 사용자 스레드에 백그라운드 지원 및 서비스를 제공하는 우선순위가 낮은 스레드입니다. 프로그램이 데몬 스레드에만 남아 있고 다른 모든 사용자 스레드는 종료/죽는 경우 데몬 스레드는 JVM에 의해 자동으로 종료됩니다. Thread 클래스에는 데몬 스레드에 대한 두 가지 메서드가 있습니다.

    공개 무효 setDaemon(부울 상태):스레드 데몬 스레드 또는 사용자 스레드를 표시하는 데 사용됩니다.공개 부울 isDaemon():스레드가 데몬인지 확인합니다.
자세한 내용은.

18)스레드가 시작되면 사용자 스레드를 데몬 스레드로 만들 수 있나요?

아니요, 그렇게 하면 IllegalThreadStateException이 발생합니다. 따라서 스레드를 시작하기 전에만 데몬 스레드를 생성할 수 있습니다.

 class Testdaemon1 extends Thread{ public void run(){ System.out.println('Running thread is daemon...'); } public static void main (String[] args) { Testdaemon1 td= new Testdaemon1(); td.start(); setDaemon(true);// It will throw the exception: td. } } 

산출

 Running thread is daemon... Exception in thread 'main' java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Thread.java:1359) at Testdaemon1.main(Testdaemon1.java:8) 
자세한 내용은.

19) 종료 후크란 무엇입니까?

종료 후크는 JVM이 종료되기 전에 암시적으로 호출되는 스레드입니다. 따라서 이를 사용하여 JVM이 정상적으로 또는 갑자기 종료될 때 리소스 정리를 수행하거나 상태를 저장할 수 있습니다. 다음 방법을 사용하여 종료 후크를 추가할 수 있습니다.

 public�void�addShutdownHook(Thread�hook){}�� Runtime r=Runtime.getRuntime(); r.addShutdownHook(new MyThread()); 

종료 후크에 대한 몇 가지 중요한 사항은 다음과 같습니다.

  • 종료 후크가 초기화되었지만 JVM 종료가 발생한 경우에만 시작할 수 있습니다.
  • 종료 후크가 실행되지 않을 가능성이 매우 적기 때문에 종료 후크는 finalizer()보다 더 안정적입니다.
  • Runtime 클래스의 Halt(int) 메소드를 호출하여 종료 후크를 중지할 수 있습니다.
자세한 내용은.

20) 언제 스레드를 중단해야 합니까?

스레드의 절전 또는 대기 상태를 해제하려면 스레드를 중단해야 합니다. InterruptedException을 발생시키는 Interrupt()를 호출하여 스레드를 중단할 수 있습니다.

자세한 내용은.

21) 동기화란 무엇입니까?

동기화는 공유 리소스에 대한 여러 스레드의 액세스를 제어하는 ​​기능입니다. 그것은 사용됩니다:


  1. 스레드 간섭을 방지합니다.
  2. 일관성 문제를 방지하기 위해.

여러 스레드가 동일한 작업을 수행하려고 하면 잘못된 결과가 발생할 가능성이 있으므로 이 문제를 해결하기 위해 Java는 한 번에 하나의 스레드만 실행되도록 허용하는 동기화 프로세스를 사용합니다. 동기화는 세 가지 방법으로 수행할 수 있습니다.

  • 동기화된 방식으로
  • 동기화된 블록별
  • 정적 동기화로

동기화된 블록의 구문

 synchronized(object reference expression) { //code block } 
자세한 내용은.

22) 동기화된 블록의 목적은 무엇입니까?

동기화된 블록은 메서드의 특정 리소스에 대해 동기화를 수행하는 데 사용될 수 있습니다. 특정 리소스에서는 한 번에 하나의 스레드만 실행할 수 있으며 동기화된 블록에 들어가려고 시도하는 다른 모든 스레드는 차단됩니다.

  • 동기화된 블록은 공유 리소스에 대한 개체를 잠그는 데 사용됩니다.
  • 동기화된 블록의 범위는 해당 블록이 적용되는 블록으로 제한됩니다. 그 범위는 메소드보다 작습니다.
자세한 내용은.

23) 특정 스레드에서 독점적으로 사용하기 위해 Java 개체를 잠글 수 있습니까?

예. 객체를 '동기화' 블록에 넣어 잠글 수 있습니다. 잠긴 개체는 명시적으로 요청한 스레드 이외의 다른 스레드에서 액세스할 수 없습니다.


24) 정적 동기화란 무엇입니까?

정적 메서드를 동기화된 것으로 만들면 잠금은 개체가 아닌 클래스에 설정됩니다. 메서드 앞에 동기화 키워드를 사용하면 개체가 잠기게 됩니다(한 번에 하나의 스레드가 개체에 액세스할 수 있음). 그러나 정적 동기화를 사용하면 클래스가 잠깁니다(한 번에 하나의 스레드가 클래스에 액세스할 수 있음). 자세한 내용은.


25)notify()와 informAll()의 차이점은 무엇입니까?

inform()은 하나의 대기 스레드를 차단 해제하는 데 사용되는 반면, informAll() 메소드는 대기 상태에 있는 모든 스레드를 차단 해제하는 데 사용됩니다.


26) 교착 상태는 무엇입니까?

교착 상태는 모든 스레드가 다른 대기 스레드가 보유한 리소스를 기다리는 상황입니다. 이 상황에서는 스레드가 실행되지도 않고 실행될 기회도 얻지 못합니다. 대신, 모든 스레드 간에 보편적인 대기 상태가 존재합니다. 교착 상태는 런타임에 코드를 손상시킬 수 있는 매우 복잡한 상황입니다.

자세한 내용은.

27) 교착 상태를 감지하는 방법은 무엇입니까? 어떻게 피할 수 있습니까?

cmd에서 코드를 실행하고 스레드 덤프를 수집하여 교착 상태를 감지할 수 있으며, 코드에 교착 상태가 있으면 cmd에 메시지가 나타납니다.

Java에서 교착 상태를 방지하는 방법:

    중첩된 잠금을 피하세요.중첩 잠금은 다양한 스레드에 잠금을 제공할 때 교착 상태가 발생하므로 특정 시간에 하나의 스레드에만 하나의 잠금을 제공해야 하기 때문에 교착 상태가 발생하는 일반적인 이유입니다.불필요한 잠금을 피하세요.필요하지 않은 잠금은 피해야 합니다.스레드 조인 사용:스레드 조인은 다른 스레드가 실행을 완료하지 않을 때까지 스레드를 기다리는 데 도움이 되므로 조인 방법을 최대한 사용하여 교착 상태를 피할 수 있습니다.

28) 자바의 스레드 스케줄러란 무엇입니까?

Java에서는 스레드를 생성할 때 JVM의 일부인 스레드 스케줄러의 도움으로 스레드를 감독합니다. 스레드 스케줄러는 실행할 스레드를 결정하는 역할만 담당합니다. 스레드 스케줄러는 스레드를 예약하기 위해 선점형과 시간 분할이라는 두 가지 메커니즘을 사용합니다.

Java 스레드 스케줄러는 스레드에 대해 다음을 결정하는 데에도 작동합니다.
  • 스레드의 우선순위를 선택합니다.
  • 스레드의 대기 시간을 결정합니다.
  • 스레드의 특성을 확인합니다.

29) 멀티스레드 프로그래밍에서는 각 스레드에 스택이 있습니까?

예, 멀티스레드 프로그래밍에서는 모든 스레드가 메모리에 자체 또는 별도의 스택 영역을 유지하므로 모든 스레드는 서로 독립적입니다.


30) 스레드의 안전성은 어떻게 달성됩니까?

경쟁 조건 없이 한 번에 여러 스레드에서 메서드나 클래스 개체를 사용할 수 있는 경우 해당 클래스는 스레드로부터 안전합니다. 스레드 안전성은 다중 스레드 프로그래밍에서 프로그램을 안전하게 사용하는 데 사용됩니다. 이는 다음과 같은 방법으로 달성할 수 있습니다.

  • 동기화
  • 휘발성 키워드 사용
  • 잠금 기반 메커니즘 사용
  • 원자 래퍼 클래스 사용

31) 경쟁 조건이란 무엇입니까?

경쟁 조건(Race Condition)은 다중 스레드 프로그래밍에서 여러 스레드가 동시에 공유 리소스에 액세스하여 실행될 때 발생하는 문제입니다. 동기화를 적절히 사용하면 Race Condition을 피할 수 있습니다.


32) 자바의 휘발성 키워드는 무엇입니까?

휘발성 키워드는 다중 스레드 프로그래밍에서 스레드 안전성을 달성하는 데 사용됩니다. 하나의 휘발성 변수의 변경 사항이 다른 모든 스레드에 표시되어 한 번에 하나의 스레드에서 하나의 변수를 사용할 수 있기 때문입니다.


33) 쓰레드풀(Thread Pool)이란 무엇을 이해하는가?

  • Java 스레드 풀은 작업 할당을 기다리는 작업자 스레드 그룹을 나타냅니다.
  • 스레드 풀의 스레드는 풀에서 하나의 스레드를 가져와 작업을 할당하는 서비스 공급자에 의해 감독됩니다.
  • 주어진 작업이 완료된 후 스레드가 다시 스레드 풀에 들어왔습니다.
  • 스레드 풀의 크기는 실행을 위해 예약되어 있는 총 스레드 수에 따라 달라집니다.

스레드 풀의 장점은 다음과 같습니다.

  • 스레드 풀을 사용하면 성능을 향상시킬 수 있습니다.
  • 스레드 풀을 사용하면 시스템 안정성이 향상될 수 있습니다.

동시 인터뷰 질문

34) 동시성 API의 주요 구성요소는 무엇입니까?

Concurrency API는 java.util.Concurrent 패키지의 클래스와 인터페이스를 이용하여 개발할 수 있습니다. java.util.Concurrent 패키지에는 다음과 같은 클래스와 인터페이스가 있습니다.

  • 집행자
  • FarkJoinPool
  • 실행자 서비스
  • ScheduledExecutorService
  • 미래
  • TimeUnit(열거형)
  • 카운트다운래치
  • 순환 장벽
  • 신호기
  • 스레드팩토리
  • 차단 대기열
  • 지연 대기열
  • 자물쇠
  • 페이저

35) Java Concurrency API의 Executor 인터페이스는 무엇입니까?

java.util.concurrent 패키지에서 제공하는 실행자 인터페이스는 새 작업을 실행하는 데 사용되는 간단한 인터페이스입니다. Executor 인터페이스의 executor() 메소드는 특정 명령을 실행하는 데 사용됩니다. Execution() 메소드의 구문은 다음과 같습니다.

void 실행(실행 가능한 명령)

디렉토리 이름 변경 리눅스

다음 예를 고려하십시오.

 import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { Executor e = Executors.newCachedThreadPool(); e.execute(new Thread()); ThreadPoolExecutor pool = (ThreadPoolExecutor)e; pool.shutdown(); } static class Thread implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 5); System.out.println('Running Thread!'); TimeUnit.SECONDS.sleep(duration); System.out.println('Thread Completed'); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } 

산출

 Running Thread! Thread Completed 

36) BlockingQueue란 무엇입니까?

java.util.concurrent.BlockingQueue는 새 값을 삽입하기 전에 공간 가용성을 기다리거나 요소를 검색하기 전에 대기열이 비어 있지 않을 때까지 기다리는 것과 같은 작업을 지원하는 Queue의 하위 인터페이스입니다. 다음 예를 고려하십시오.

 import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { BlockingQueue queue = new ArrayBlockingQueue(10); Insert i = new Insert(queue); Retrieve r = new Retrieve(queue); new Thread(i).start(); new Thread(r).start(); Thread.sleep(2000); } static class Insert implements Runnable { private BlockingQueue queue; public Insert(BlockingQueue queue) { this.queue = queue; } @Override public void run() { Random random = new Random(); try { int result = random.nextInt(200); Thread.sleep(1000); queue.put(result); System.out.println('Added: ' + result); result = random.nextInt(10); Thread.sleep(1000); queue.put(result); System.out.println('Added: ' + result); result = random.nextInt(50); Thread.sleep(1000); queue.put(result); System.out.println('Added: ' + result); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Retrieve implements Runnable { private BlockingQueue queue; public Retrieve(BlockingQueue queue) { this.queue = queue; } @Override public void run() { try { System.out.println('Removed: ' + queue.take()); System.out.println('Removed: ' + queue.take()); System.out.println('Removed: ' + queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } } } 

산출

 Added: 96 Removed: 96 Added: 8 Removed: 8 Added: 5 Removed: 5 

37) BlockingQueue를 사용하여 생산자-소비자 문제를 구현하는 방법은 무엇입니까?

생산자-소비자 문제는 다음과 같은 방법으로 BlockingQueue를 사용하여 해결할 수 있습니다.

 import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; public class ProducerConsumerProblem { public static void main(String args[]){ //Creating shared object BlockingQueue sharedQueue = new LinkedBlockingQueue(); //Creating Producer and Consumer Thread Thread prod = new Thread(new Producer(sharedQueue)); Thread cons = new Thread(new Consumer(sharedQueue)); //Starting producer and Consumer thread prod.start(); cons.start(); } } //Producer Class in java class Producer implements Runnable { private final BlockingQueue sharedQueue; public Producer(BlockingQueue sharedQueue) { this.sharedQueue = sharedQueue; } @Override public void run() { for(int i=0; i<10; i++){ try { system.out.println('produced: ' + i); sharedqueue.put(i); } catch (interruptedexception ex) logger.getlogger(producer.class.getname()).log(level.severe, null, ex); consumer class in java implements runnable{ private final blockingqueue sharedqueue; public (blockingqueue sharedqueue) this.sharedqueue="sharedQueue;" @override void run() while(true){ system.out.println('consumed: '+ sharedqueue.take()); logger.getlogger(consumer.class.getname()).log(level.severe, < pre> <p> <strong>Output</strong> </p> <pre> Produced: 0 Produced: 1 Produced: 2 Produced: 3 Produced: 4 Produced: 5 Produced: 6 Produced: 7 Produced: 8 Produced: 9 Consumed: 0 Consumed: 1 Consumed: 2 Consumed: 3 Consumed: 4 Consumed: 5 Consumed: 6 Consumed: 7 Consumed: 8 Consumed: 9 </pre> <hr> <h3>38) What is the difference between Java Callable interface and Runnable interface?</h3> <p>The Callable interface and Runnable interface both are used by the classes which wanted to execute with multiple threads. However, there are two main differences between the both : </p> <ul> <li>A Callable interface can return a result, whereas the Runnable interface cannot return any result.</li> <li>A Callable interface can throw a checked exception, whereas the Runnable interface cannot throw checked exception. </li> <li>A Callable interface cannot be used before the Java 5 whereas the Runnable interface can be used.</li> </ul> <hr> <h3>39) What is the Atomic action in Concurrency in Java?</h3> <ul> <li>The Atomic action is the operation which can be performed in a single unit of a task without any interference of the other operations.</li> <li>The Atomic action cannot be stopped in between the task. Once started it fill stop after the completion of the task only. </li> <li>An increment operation such as a++ does not allow an atomic action.</li> <li>All reads and writes operation for the primitive variable (except long and double) are the atomic operation.</li> <li>All reads and writes operation for the volatile variable (including long and double) are the atomic operation.</li> <li>The Atomic methods are available in java.util.Concurrent package. </li> </ul> <hr> <h3>40) What is lock interface in Concurrency API in Java?</h3> <p>The java.util.concurrent.locks.Lock interface is used as the synchronization mechanism. It works similar to the synchronized block. There are a few differences between the lock and synchronized block that are given below.</p> <ul> <li>Lock interface provides the guarantee of sequence in which the waiting thread will be given the access, whereas the synchronized block doesn&apos;t guarantee it.</li> <li>Lock interface provides the option of timeout if the lock is not granted whereas the synchronized block doesn&apos;t provide that.</li> <li>The methods of Lock interface, i.e., Lock() and Unlock() can be called in different methods whereas single synchronized block must be fully contained in a single method.</li> </ul> <hr> <h3>41) Explain the ExecutorService Interface.</h3> <p>The ExecutorService Interface is the subinterface of Executor interface and adds the features to manage the lifecycle. Consider the following example.</p> <pre> import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService e = Executors.newSingleThreadExecutor(); try { e.submit(new Thread()); System.out.println(&apos;Shutdown executor&apos;); e.shutdown(); e.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { System.err.println(&apos;tasks interrupted&apos;); } finally { if (!e.isTerminated()) { System.err.println(&apos;cancel non-finished tasks&apos;); } e.shutdownNow(); System.out.println(&apos;shutdown finished&apos;); } } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 20); System.out.println(&apos;Running Task!&apos;); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } </pre> <p> <strong>Output</strong> </p> <pre> Shutdown executor shutdown finished </pre> <hr> <h3>42) What is the difference between Synchronous programming and Asynchronous programming regarding a thread?</h3> <p> <strong>Synchronous programming: </strong> In Synchronous programming model, a thread is assigned to complete a task and hence thread started working on it, and it is only available for other tasks once it will end the assigned task.</p> <p> <strong>Asynchronous Programming: </strong> In Asynchronous programming, one job can be completed by multiple threads and hence it provides maximum usability of the various threads.</p> <hr> <h3>43) What do you understand by Callable and Future in Java?</h3> <p> <strong>Java Callable interface: </strong> In Java5 callable interface was provided by the package java.util.concurrent. It is similar to the Runnable interface but it can return a result, and it can throw an Exception. It also provides a run() method for execution of a thread. Java Callable can return any object as it uses Generic.</p> <p> <strong>Syntax:</strong> </p> <p>public interface Callable</p> <p> <strong>Java Future interface:</strong> Java Future interface gives the result of a concurrent process. The Callable interface returns the object of java.util.concurrent.Future.</p> <p>Java Future provides following methods for implementation.</p> <ul> <tr><td>cancel(boolean&#xFFFD;mayInterruptIfRunning):</td> It is used to cancel the execution of the assigned task. </tr><tr><td>get():</td> It waits for the time if execution not completed and then retrieved the result. </tr><tr><td>isCancelled():</td> It returns the Boolean value as it returns true if the task was canceled before the completion. </tr><tr><td>isDone():</td> It returns true if the job is completed successfully else returns false. </tr></ul> <hr> <h3>44. What is the difference between ScheduledExecutorService and ExecutorService interface?</h3> <p>ExecutorServcie and ScheduledExecutorService both are the interfaces of java.util.Concurrent package but scheduledExecutorService provides some additional methods to execute the Runnable and Callable tasks with the delay or every fixed time period.</p> <h3>45) Define FutureTask class in Java? </h3> <p>Java FutureTask class provides a base implementation of the Future interface. The result can only be obtained if the execution of one task is completed, and if the computation is not achieved then get method will be blocked. If the execution is completed, then it cannot be re-started and can&apos;t be canceled.</p> <p> <strong>Syntax</strong> </p> <p>public class FutureTask extends Object implements RunnableFuture</p> <hr></10;>

38) Java Callable 인터페이스와 Runnable 인터페이스의 차이점은 무엇입니까?

Callable 인터페이스와 Runnable 인터페이스는 모두 여러 스레드로 실행하려는 클래스에서 사용됩니다. 그러나 둘 사이에는 두 가지 주요 차이점이 있습니다.

  • Callable 인터페이스는 결과를 반환할 수 있지만 Runnable 인터페이스는 결과를 반환할 수 없습니다.
  • Callable 인터페이스는 확인된 예외를 발생시킬 수 있지만 Runnable 인터페이스는 확인된 예외를 발생시킬 수 없습니다.
  • Callable 인터페이스는 Java 5 이전에는 사용할 수 없지만 Runnable 인터페이스는 사용할 수 있습니다.

39) Java 동시성에서 원자적 동작이란 무엇입니까?

  • Atomic Action은 다른 작업의 간섭 없이 단일 작업 단위로 수행할 수 있는 작업입니다.
  • 작업 사이에 원자적 작업을 중지할 수 없습니다. 일단 시작되면 작업이 완료된 후에만 채우기가 중지됩니다.
  • a++와 같은 증분 연산은 원자적 동작을 허용하지 않습니다.
  • 기본 변수에 대한 모든 읽기 및 쓰기 작업(long 및 double 제외)은 원자 작업입니다.
  • 휘발성 변수(long 및 double 포함)에 대한 모든 읽기 및 쓰기 작업은 원자 작업입니다.
  • Atomic 메소드는 java.util.Concurrent 패키지에서 사용할 수 있습니다.

40) Java Concurrency API의 잠금 인터페이스란 무엇입니까?

java.util.concurrent.locks.Lock 인터페이스는 동기화 메커니즘으로 사용됩니다. 이는 동기화된 블록과 유사하게 작동합니다. 아래에 제시된 잠금 블록과 동기화 블록 사이에는 몇 가지 차이점이 있습니다.

  • 잠금 인터페이스는 대기 중인 스레드에 액세스 권한이 부여되는 순서를 보장하는 반면, 동기화된 블록은 이를 보장하지 않습니다.
  • 잠금 인터페이스는 잠금이 부여되지 않은 경우 시간 초과 옵션을 제공하는 반면 동기화된 블록은 이를 제공하지 않습니다.
  • Lock 인터페이스의 메소드, 즉 Lock() 및 Unlock()은 서로 다른 메소드로 호출될 수 있지만 단일 동기화 블록은 단일 메소드에 완전히 포함되어야 합니다.

41) ExecutorService 인터페이스를 설명하세요.

ExecutorService 인터페이스는 Executor 인터페이스의 하위 인터페이스로 라이프사이클을 관리하는 기능을 추가합니다. 다음 예를 고려하십시오.

 import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { ExecutorService e = Executors.newSingleThreadExecutor(); try { e.submit(new Thread()); System.out.println(&apos;Shutdown executor&apos;); e.shutdown(); e.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { System.err.println(&apos;tasks interrupted&apos;); } finally { if (!e.isTerminated()) { System.err.println(&apos;cancel non-finished tasks&apos;); } e.shutdownNow(); System.out.println(&apos;shutdown finished&apos;); } } static class Task implements Runnable { public void run() { try { Long duration = (long) (Math.random() * 20); System.out.println(&apos;Running Task!&apos;); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } 

산출

 Shutdown executor shutdown finished 

42) 스레드에 관한 동기 프로그래밍과 비동기 프로그래밍의 차이점은 무엇입니까?

동기식 프로그래밍: 동기식 프로그래밍 모델에서는 작업을 완료하기 위해 스레드가 할당되어 스레드가 작업을 시작했으며 할당된 작업이 종료된 후에만 다른 작업에 사용할 수 있습니다.

비동기 프로그래밍: 비동기 프로그래밍에서는 하나의 작업이 여러 스레드에 의해 완료될 수 있으므로 다양한 스레드의 활용도가 최대화됩니다.


43) Java에서 Callable과 Future를 어떻게 이해하시나요?

Java 호출 가능 인터페이스: Java5에서는 호출 가능한 인터페이스가 java.util.concurrent 패키지에 의해 제공되었습니다. Runnable 인터페이스와 유사하지만 결과를 반환할 수 있고 예외를 발생시킬 수 있습니다. 또한 스레드 실행을 위한 run() 메서드도 제공합니다. Java Callable은 Generic을 사용하므로 모든 객체를 반환할 수 있습니다.

자바 의사코드

통사론:

공개 인터페이스 호출 가능

자바 미래 인터페이스: Java Future 인터페이스는 동시 프로세스의 결과를 제공합니다. Callable 인터페이스는 java.util.concurrent.Future의 객체를 반환합니다.

Java Future는 구현을 위해 다음과 같은 방법을 제공합니다.

    취소(boolean�mayInterruptIfRunning):할당된 작업의 실행을 취소하는데 사용됩니다.얻다():실행이 완료되지 않은 경우 시간을 기다린 후 결과를 가져옵니다.취소됨():작업이 완료되기 전에 취소된 경우 true를 반환하므로 부울 값을 반환합니다.수행():작업이 성공적으로 완료되면 true를 반환하고 그렇지 않으면 false를 반환합니다.

44. ScheduledExecutorService와 ExecutorService 인터페이스의 차이점은 무엇입니까?

ExecutorServcie 및 ScheduledExecutorService는 모두 java.util.Concurrent 패키지의 인터페이스이지만 ScheduledExecutorService는 지연 또는 매 고정 기간마다 Runnable 및 Callable 작업을 실행하기 위한 몇 가지 추가 메서드를 제공합니다.

45) Java에서 FutureTask 클래스를 정의하시겠습니까?

Java FutureTask 클래스는 Future 인터페이스의 기본 구현을 제공합니다. 하나의 작업 실행이 완료된 경우에만 결과를 얻을 수 있으며, 계산이 이루어지지 않으면 get 메서드가 차단됩니다. 실행이 완료되면 다시 시작할 수 없으며 취소할 수도 없습니다.

통사론

공개 클래스 FutureTask는 Object를 확장하여 RunnableFuture를 구현합니다.