Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 894
ilija Avatar asked Jun 12 '26 22:06

ilija


1 Answers

You can't just stop any thread*. You can try interrupting it:

t.interrupt();

But the thread has to be able to handle it. This brings a question, what does:

StreamingExperiment.streamingExperimentMain();

actually do? If it performs CPU intensive operations, the thread must periodically check isInterrupted() flag and terminate if it happens to be set. If it waits on I/O or sleeps, chances are it will just work - see InterruptedException.

Well, technically you can, but this method is deprecated for a reason.

like image 116
Tomasz Nurkiewicz Avatar answered Jun 15 '26 12:06

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!