java - 线程中的 Stop() 方法?

标签 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.");
   }
}

最佳答案

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

关于java - 线程中的 Stop() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038063/

相关文章:

java - 从 AppEngine Dev Server 运行任意 Java

java - 如何从 XML 文件中删除多余的空行?

c - errno 是线程安全的吗?

android - 为什么创建 C++11 线程会导致致命信号?

java - ReadWriteLocks-(不可重入)它如何支持多个读者获取读锁

Java 动画程序在 Linux 中运行不流畅

java - 将包安排到 'reverse URL notation' : cant get the main class to run

java - 使用 jnlp 获取 java applet 在浏览器中运行

java - 线程安全单例类

java - 从多线程读取一个HashMap会有问题吗?