2017-11-15 7 views
0

- 대기 (없이) 통지() 메소드 :동일한 잠금 장치를 가진 하나의 스레드가 잠자고있는 동안 다른 스레드가 잠금을 획득 할 수있는 것처럼 보이는 것은 어떻습니까? 코드 아래

package com.jay; 

import java.util.Random; 

public class Main { 

    public static void main(String[] args) { 
     Message message = new Message(); 
     (new Thread(new Writer(message))).start(); 
     (new Thread(new Reader(message))).start(); 
    } 

} 

class Message { 
    private String message; 
    private boolean empty = true; 

    public synchronized String read() { 
     while (empty) { 

     } 
     empty = true; 
     return message; 
    } 

    public synchronized void write(String message) { 
     while (!empty) { 

     } 
     empty = false; 
     this.message = message; 
    } 
} 

class Writer implements Runnable { 
    private Message message; 

    public Writer(Message message) { 
     this.message = message; 
    } 

    public void run() { 
     String[] messages = { 
      "Humpty Dumpty sat on a wall", 
      "Humpty Dumpty had a great fall", 
      "All the king's horses and all the king's men", 
      "Couldn't put Humpty together again" 
     }; 

     Random random = new Random(); 

     for(int i=0; i<messages.length; i++) { 
      message.write(messages[i]); 
      try { 
       Thread.sleep(random.nextInt(2000)); 
      } catch (InterruptedException e) { 
       // TODO: handle exception 
      } 
     } 
     message.write("Finished"); 
    } 
} 

class Reader implements Runnable { 
    private Message message; 

    public Reader(Message message) { 
     this.message = message; 
    } 

    public void run() { 
     Random random = new Random(); 

     for(String latestMessage = message.read(); !latestMessage.equals("Finished"); 
       latestMessage = message.read()) { 
      System.out.println(latestMessage); 

      try { 
       Thread.sleep(random.nextInt(2000)); 
      } catch (InterruptedException e) { 
       // TODO: handle exception 
      } 
     } 
    } 
} 

그것은 콘솔 아래에 인쇄 - 시간 및 중단의 가장 :

Humpty Dumpty sat on a wall 

Humpty Dumpty had a great fall 

을하고 몇 번이 모두를 인쇄 네 개의 메시지.

내 질문은 : Writer 스레드가 이미 잠금을 획득하고 계속 반복하면서 Reader 스레드가 read() 메서드에서 코드를 실행할 수 있습니까?

혼란 스럽습니다. 이해 좀 도와주세요!

+1

"잠금"이란 'Message'의 메소드가 동기화되어 있다는 의미입니다. 맞습니까? 독자가 동기화 된 메서드를 종료 할 때마다 동기화 된 메서드를 입력 할 수 있습니다. 즉 중간의 메소드 호출. –

+0

오 이런! 어떻게 내가 이것을 놓칠 수 있냐?! '작가는 동기화 된 메서드를 떠날 때마다 동기화 된 메서드를 입력 할 수 있습니다. 즉 중간의 메소드 호출. 이것은 내 의문에 대답했습니다. 메서드가 실행 된 후에 잠금이 해제되었음을 어떻게 든 알 수 없었습니다. 고마워요! – hermit05

답변

0

@ 올리버 찰스 워스의 의견이 내 의구심을 제거했습니다. 필자가 동기화 된 메서드를 종료 할 때마다 독자가 동기화 된 메서드에 들어갈 수 있다는 것을 알지 못했습니다. 한 스레드에서 잠자고 "빈"필드의 값이 수정되지 않아 무한 루프가 실행되는 단계가 있기 때문에 프로그램이 중단됩니다. wait() 및 notify() 메서드가 구현되면 문제가 해결됩니다!