Search code examples
javamultithreadingdestroy

Stop the ongoing process(Thread) in Java on button click


I have the following two buttons:

 jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {

            Thread t = new Thread() {
                public void run() {
                    StreamingExperiment.streamingExperimentMain();
                }
            };
            t.setName("runThread");
            t.start();

        }
    });

and

 jButton3.setText("Cancel");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {

        }
    });

JButton3 is actually a cancel button which has to cancel the ongoing StreamingExperiment. How I am supposed to stop ongoing thread in this situation?


Solution

  • You'd have the JButton's ActionListener call:

    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StreamingExperiment.stop();
        }
    });
    

    You'll of course need to give StreamingExperiment this method whose contents will all depend on what StreamingExperiment does. If it has a loop, then perhaps stop() can change a boolean that you use to exit the loop.

    By the way, it looks like StreamingExperiment has a static method, and you might want to fix this (unless it represents a variable, not a class in which case you should have its name start with a lower-case letter).