1

I am having a problem trying to stop a thread instantly after a certain amount of time has elapsed, because thread.stop and similar others have been depreciated.

The thread that I am trying to stop uses my mouse and I need to stop it so that I can use my mouse in other ways.

What I was thinking is the code below, which was just to make another thread to watch how long the main thread has been running and if it is alive, stop it, but I can't accomplish this.

public void threadRun(int a) {
    Thread mainThread = new Thread(new Runnable() {
        @Override
        public void run() {
            // does things with mouse which may need to be ended while they
            // are in action
        }
    });

    Thread watchThread = new Thread(new Runnable() {
        @Override
        public void run() {
            if (timeFromMark(mark) > a) {
                if (mainThread.isAlive()) {
                    // How can I stop the mainThread?
                }
            }

        }
    });

}
user2510325
  • 127
  • 1
  • 8

3 Answers3

2

You need to define a class for your second thread that extends runnable and pass the first thread as an argument.

Then you can stop the first thread.

But instead of doing this manually, have a look at the Java ThreadPoolExecuter and its awaitTermination(long timeout, TimeUnit unit) method. (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html )

Will save a lot of work.

    ExecutorService executor = Executors.newFixedThreadPool(1);

    Runnable r = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                System.out.println("doing stuff");
                Thread.sleep(10000);
                System.out.println("finished");
            } catch (InterruptedException e) {
                System.out.println("Interrupted before finished!");
            }
        }
    };

    executor.execute(r);
    executor.shutdown();
    try {
        executor.awaitTermination(1, TimeUnit.SECONDS);
        executor.shutdownNow();
    } catch (InterruptedException e) {
        //
    }
    System.out.println("Thread worker forced down. Continue with Application...");

Produces:

doing stuff
Interrupted before finished!
Thread worker forced down. Continue with Application...

Last two messages are nearly equal in terms of time and may change positions (its two different threads, continuing)

dognose
  • 20,360
  • 9
  • 61
  • 107
  • I couldn't seem to be able to configure this properly...I can only implement runnable and the executors are not compiling. I think I have found another way, though, thanks. – user2510325 Jan 21 '14 at 19:50
0

Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).

Taken from How do I kill a thread from another thread in Java?

Community
  • 1
  • 1
Zzyrk
  • 907
  • 8
  • 16
0

Killing/stopping threads is a bad idea. That's why they deprecated those methods. It's better to ask the thread to stop. E.g., something like the example below. (But note: if "do_something()" takes a long time, then you might want to use an interrupt to abort whatever it is.)

import java.util.concurrent.atomic.AtomicBoolean;

public class Stoppable {
    private AtomicBoolean timeToDie = new AtomicBoolean(false);
    private Thread thread;

    public void start() {
        if (thread != null) {
            throw new IllegalStateException("already running");
        }
        thread = new Thread(new Runnable() {
            public void run() {
                while (!timeToDie.get()) {
                    // do_something();
                }
            }
        });
        thread.start();
    }

    public void stop() throws InterruptedException {
        timeToDie.set(true);
        thread.join();
        thread = null;
    }
}
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57