简体   繁体   中英

Stop() method in a thread?

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

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

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

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

Calling stop method will kill the thread on which it is called. A thread must only be killed when there is no use of continuing what a thread is doing. When you will call the stop method, the Thread will stop its execution and will die.

It is preferable to allow thread to complete its run method and kill itslef rather than killing it forcefully.

Calling stop() triggers an exception/error to be thrown in the thread at a random point. If you have access to all the code for the thread it can be used safely, however if this the case, you are far better off supporting interrupts.

Instead of Object.wait/notify, you are likely to be better off using high level concurrency library support ie use a Lock which would simplify your code.

For more on stop(); Does Thread.stop() really stop a Thread?

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);
        }
    }
}         

It depends on your threads and what they have to do really.

If they are workers that for example listen to a tcp/ip socket, then you're better off having a volatile boolean inside of the class that says wether or not the loop inside your run() method should continue. Then have your class that extends thread implement a pleaseStop() function which puts the boolean to false, which then causes your run method to finish gracefully (you can even clean up your resources then).

On the other hand, if they are workers that have a finite amount of work to be done, then you should just wait for them to be ready, using the join() functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM