Login  Register

Re: Any way to Kill a thread?

Posted by dscho on Jul 16, 2008; 11:49am
URL: http://imagej.273.s1.nabble.com/Any-way-to-Kill-a-thread-tp3695586p3695587.html

Hi,

On Tue, 15 Jul 2008, John Alexander wrote:

> If the plug-in does not respond to "closing" nor does it have a "cancel"
> option - is there anyway of aborting a thread?

I wrote a really simple plugin to do that some time ago:

-- snip --
import ij.IJ;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;

public class Thread_Killer implements PlugIn {
        public void run(String arg) {
                ThreadGroup group = Thread.currentThread().getThreadGroup();
                int activeCount = group.activeCount();
                Thread[] threads = new Thread[activeCount];
                group.enumerate(threads);
                int j = 0;
                for (int i = 0; i < activeCount; i++) {
                        String name = threads[i].getName();
                        if (threads[i] == Thread.currentThread() ||
                                        name.startsWith("AWT-") ||
                                        name.equals("Java2D Disposer") ||
                                        name.equals("SocketListener") ||
                                        name.equals("DestroyJavaVM") ||
                                        name.equals("TimerQueue"))
                                continue;
                        if (j < i)
                                threads[j] = threads[i];
                        System.err.println("nr " + i + ": " + threads[i].getName());
                        j++;
                }
                activeCount = j;
                if (activeCount == 0) {
                        IJ.showMessage("No threads to kill.");
                        return;
                }

                String[] names = new String[activeCount];
                for (int i = 0; i < activeCount; i++)
                        names[i] = threads[i].getName();
                GenericDialog gd = new GenericDialog("Thread to kill");
                gd.addChoice("thread", names, names[0]);
                gd.showDialog();
                if (gd.wasCanceled())
                        return;
                int threadIndex = gd.getNextChoiceIndex();
                threads[threadIndex].stop();
        }
}
-- snap --

If you have a JDK (as opposed to just a JRE) you can make a new plugin
without restarting ImageJ, paste the code, compile and run it.

May it help,
Dscho