线程中的Stop()方法?

时间:2011-08-12 09:21:49

标签: java multithreading

在下面的示例中,如何实现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.");
   }
}

5 个答案:

答案 0 :(得分:6)

如果线程返回run()函数,线程会自动停止。不需要使用stop()函数,因为java不推荐使用stop方法而且使用不安全

答案 1 :(得分:1)

调用stop方法将终止调用它的线程。只有在没有继续使用线程正在执行的操作时,才能杀死线程。当您调用stop方法时,Thread将停止执行并将死亡。

最好允许线程完成其run方法并杀死它而不是强行杀死它。

答案 2 :(得分:1)

调用stop()会触发在随机点的线程中抛出异常/错误。如果您可以访问该线程的所有代码,则可以安全地使用它,但是如果是这种情况,那么您最好不要支持中断。

而不是Object.wait / notify,您可能最好使用高级并发库支持,即使用可以简化代码的Lock。

有关stop()的更多信息; Does Thread.stop() really stop a Thread?

答案 3 :(得分:0)

这取决于你的线程以及他们必须做的事情。

如果他们是工作人员,例如监听tcp / ip套接字,那么你最好在类中包含一个不稳定的boolean,或者说run()方法中的循环应该继续。然后让你的类扩展线程实现一个pleaseStop()函数,它将布尔值设置为false,然后使你的run方法优雅地完成(你甚至可以清理你的资源)。

另一方面,如果他们是工作量有限的工人,那么你应该等待他们准备好,使用join()功能。

答案 4 :(得分: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);
        }
    }
}