2011-08-12 3 views
2

다음 예제에서는 어떻게 stop() 메서드가 구현됩니까 ??스레드에서 Stop() 메소드가 필요합니까?

stop() 메서드를 사용하는 대신 수행해야 할 작업은 무엇입니까?

제 생각에 원하는 상태가 일시 중단되면 스레드는 Object.wait을 사용하여 대기합니다. 스레드가 다시 시작되면 Object.notify을 사용하여 대상 스레드에 알립니다. 아래 예제에서 stop()의 암시의 경우에 의심 스럽습니다.

Class NewThread implements Runnable { 
    String name; // name of thread 
    Thread t; 
    boolean suspendFlag; 
    NewThread(String threadname) { 
     name = threadname; 
     t = new Thread(this, name); 
     System.out.println("New thread: " + t); 
     suspendFlag = false; 
     t.start(); // Start the thread 
    } 
    // This is the entry point for thread. 
    public void run() { 
     try { 
     for(int i = 15; i > 0; i--) { 
     System.out.println(name + ": " + i); 
     Thread.sleep(200); 
     synchronized(this) { 
      while(suspendFlag) { 
       wait(); 
      } 
      } 
     } 
     } catch (InterruptedException e) { 
     System.out.println(name + " interrupted."); 
     } 
     System.out.println(name + " exiting."); 
    } 
    void mysuspend() { 
     suspendFlag = true; 
    } 
    synchronized void myresume() { 
     suspendFlag = false; 
     notify(); 
    } 
} 

class SuspendResume { 
    public static void main(String args[]) { 
     NewThread ob1 = new NewThread("One"); 
     NewThread ob2 = new NewThread("Two"); 
     try { 
     Thread.sleep(1000); 
     ob1.mysuspend(); 
     System.out.println("Suspending thread One"); 
     Thread.sleep(1000); 
     ob1.myresume(); 
     System.out.println("Resuming thread One"); 
     ob2.mysuspend(); 
     System.out.println("Suspending thread Two"); 
     Thread.sleep(1000); 
     ob2.myresume(); 
     System.out.println("Resuming thread Two"); 
     } catch (InterruptedException e) { 
     System.out.println("Main thread Interrupted"); 
     } 
     // wait for threads to finish 
     try { 
     System.out.println("Waiting for threads to finish."); 
     ob1.t.join(); 
     ob2.t.join(); 
     } catch (InterruptedException e) { 
     System.out.println("Main thread Interrupted"); 
     } 
     System.out.println("Main thread exiting."); 
    } 
} 

답변

6

는 실행() 정지 방법은 자바에 의해 사용되지 않으며 안전하지 않은 Thread.stop를가되지 않습니다

1

호출 stop 메소드가 호출되는 스레드를 죽일 것이다. thread는, thread가하고있는 것을 계속 사용하는 것이없는 경우에만, kill 될 필요가 있습니다. stop 메서드를 호출하면 스레드가 실행을 중지하고 종료됩니다.

쓰래드가 강제로 죽이는 것이 아니라 run 메소드를 완료하고 itslef를 종료하도록하는 것이 바람직합니다.

+0

를 사용하고 있기 때문에 정지() 함수를 사용할 필요가 function.no 반환하는 경우 스레드가 자동으로 중지 사용을 고려하기 전에 실제로 무엇을하는지 이해해야합니다. Thread.stop()은 항상 스레드를 중지하지는 않습니다. ;) –

+0

@Peter : 모든 조건에서 Thread.stop()은 Thread를 죽이지 않을 것인가? – Logan

+0

ThreadDeath를 잡으면 ThreadDeath 오류가 발생하고 ThreadDeath 또는 Error 또는 Throwable을 더 많이 기록하면 버려 질 수 있습니다. 자세한 내용은 내 대답의 기사를 참조하십시오. –

1

stop()을 호출하면 임의의 지점에서 스레드에 예외/오류가 throw됩니다. 스레드의 모든 코드에 액세스 할 수 있으면 안전하게 사용할 수 있지만이 경우에는 인터럽트를 지원하는 것이 훨씬 낫습니다.

Object.wait/notify 대신 높은 수준의 동시성 라이브러리 지원을 사용하는 것이 좋습니다. 즉, 코드를 단순화하는 Lock을 사용하는 것이 좋습니다.

자세한 내용은 stop(); Does Thread.stop() really stop a Thread?

0

이것은 스레드에 따라 다르며 실제로 수행해야하는 작업에 따라 다릅니다.

예를 들어 TCP/IP 소켓을 청취하는 작업자 인 경우 run() 메소드 내부의 루프가 계속 진행되어야하는지 여부를 알려주는 클래스의 휘발성 부울을 사용하는 것이 좋습니다. 그런 다음 스레드를 확장하는 클래스에 boolean을 false로 설정하는 pleaseStop() 함수를 구현하면 실행 메소드가 정상적으로 완료됩니다 (리소스를 정리할 수도 있습니다).

한편 작업량이 한정된 근로자 인 경우 join() 기능을 사용하여 작업 준비가 완료 될 때까지 기다려야합니다.

0

Thread 클래스의 stop 메소드는 잠긴 모니터를 모두 잠금 해제하기 때문에 사용하기가 더디고 안전하지 않습니다.

스레드를 중지하는 방법에 대한 몇 가지 제안은 here입니다.

0
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {            
    // TODO add your handling code here: 
    if (jToggleButton1.isSelected()) { 
     jToggleButton1.setBackground(Color.green); 
     jToggleButton1.setText("ON"); 
     //MainClass main = new MainClass(); 
     new Thread(new Runnable() { 

      @Override 
      public void run() { 
       try { 
        server = new ServerSocket(4400, 500); 
        do { 
         socket = server.accept(); 
         ClientHandler cliendHandler = new ClientHandler(socket); 
         cliendHandler.start(); 
        } while (true); 
       } catch (IOException ex) { 
       } 
      } 
     }).start(); 

    } else { 
     try { 
      server.close(); 
      jToggleButton1.setText("START SERVER"); 
      jToggleButton1.setBackground(Color.red); 
     } catch (IOException ex) { 
      Logger.getLogger(Server_Prog.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
}   
관련 문제