2013-11-09 2 views
1

이 스레드를 기다리는 중입니다.하지만 기다리지 않거나 예외를 던지거나 아무 작업도하지 않습니다. (스레드를 실행하기 위해 새 스레드를 만들었습니다. 그렇지 않으면 스레드가 실행되지 않습니다. 당신은 당신이 equals()를 사용할 필요가 문자열을 비교하지 ==Java : 스레드가 대기하지 않습니다.

if(button.getText().equals("Pause")) { 
    thread.wait(); 
    button.setText("Resume"); 

} else if(button.getText().equals("Resume")) { 
    thread.notify(); 
    button.setText("Pause"); 
} 

을하지만 대기를 사용하고 아마 정말 당신이 원하는 일을하지 않습니다 통지하는 경우 동부 서머 타임에 대기 방법)

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 

public class Sandbox extends JFrame { 

boolean paused = false; 
Thread thread = new Thread() { 
    public void run() { 
     while(true) { 
      System.out.println("running..."); 
     } 
    } 
}; 

private JButton button; 
public Sandbox() throws Exception { 
    thread.start(); 
    setSize(300, 150); 
    setLocationRelativeTo(null); 
    setDefaultCloseOperation(3); 
    add(button = new JButton("Pause")); 
    button.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
     new Thread() { 
      public void run() { 
       synchronized(thread) { 
        try { 
         if(button.getText().equals("Pause")) { 
          thread.wait(); 
          button.setText("Resume"); 

         } else if(button.getText().equals("Resume")) { 
          thread.notify(); 
          button.setText("Pause"); 
         } 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }.start(); 
    }}); 
    setVisible(true); 
} 

public static void main(String[] args) throws Exception { 
    new Sandbox(); 
} 
} 
+0

'Thread' 객체에서'wait'를 호출해서는 안됩니다. 완료 될 때까지 대기하려면'join'을 사용하십시오. 'wait/notify'는 조건 변수의 동작을하기 위해 사용됩니다. – zch

+0

나는 스레드가 죽을 것이라고 생각하지 않는다. while 루프는 무한히 계속된다. –

+0

나는'wait' 메소드가 무엇을하는지 이해하지 못한다고 생각한다. 'thread.wait()'를 호출하면 어떻게 될 것으로 예상됩니까? – zch

답변

1

를 호출.

+0

예, 이해할 수 있습니다. 이것은 문제를 해결하기위한 거친 코드 일뿐입니다. 다른 무엇을 사용할 수 있습니까? –

관련 문제