线程中的Stop()方法? [英] Stop() method in a thread?

查看:217
本文介绍了线程中的Stop()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,如何实现stop()方法?

In the following example how stop() method is implemented??

应该怎么做,而不要使用stop()方法?

What should be done instead of using stop() method?

在我看来,当所需状态挂起时,线程将使用Object.wait等待.恢复线程后,将使用Object.notify通知目标线程.但在下面的示例中,如果将stop()设置为可疑,则是可疑的.

In my point of view ,When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify. but doubtful in case of implentation of stop() in the below example.

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弃用,并且使用起来不安全

The thread automatically stop if it returns the run() function.no need to use the stop() function because stop method is deprecated by java and unsafe to use

这篇关于线程中的Stop()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆