How to stop threads in Java?

I created a java program with a graphical interface, and I need a stop button function in which, when the user presses the stop button, the program must be stopped.

  • In my program, the main thread starts the other 10 threads, and I want that whenever the stop button is pressed, all 10 threads should be stopped before the main thread.

  • Secondly, I also want that whenever any thread from these 10 threads is stopped, it must first close all the resources that it has opened before connecting to the database, etc.

I implemented the code to which I answered ........

Now there is one problem.

My stream class is as follows:

public class ParserThread implements Runnable {
    private volatile boolean stopped = false;

    public void stopTheThread() {
        stopped = true;
    }
    :
    :
}

And below is the main thread that starts 10 threads from the start () function

public class Main() {
    Thread [] threads;

    public void start() {
        for(int i = 0; i < 10; i++) {
            threads[i] = new Thread(new ParserThread());
        }       
    }

    public void stop() {
        // code to stop all the threads
    }
}

stop ParserThread, "stop = true", . , 10 .

stop. , stopAllThreads() .

+2
3

, - . , - , . Object.wait() - , , , , , . ( , - . - .)

, . , interrupt() destroy(), , IMO. ( , , - , ).

EDIT: :

// Client code
for (Task task : tasks) {
  task.stop();
}

// Threading code
public abstract class Task implements Runnable {

  private volatile boolean stopped = false;

  public void stop() {
    stopped = true;
  }

  protected boolean shouldStop() {
    return stopped;
  }

  public abstract void run();
}

Task. , , stop() , .

:

public class SomeTask extends Task {
  public void run() {
    while (!shouldStop()) {
      // Do work
    }
  }
}
+8

, . :

public class SomeTask extends Task {
   public void run() {
      while (!shouldStop()) {
        // Do work
      }
    }
  }

, "Do work" ? . .

.

0

, , , , (, , , /, , ).

-1

Source: https://habr.com/ru/post/1720863/


All Articles