Stopping threads

how to stop threads immediately?following is my threading code.when i press the stop button the game stops after one or more generations (John Conway's life game).i have tried the boolean solution i.e. declaring a boolean variable and setting it true or false to start and stop the game.is there a more powerful method than yield to stop the thread?how to solve this problem?
private Thread lifeThread=null;
//this is the code used when the start button is pressed
public void start() {
if(lifeThread == null)
lifeThread = new Thread(this);
lifeThread.start();
//this is the code for the stop button
public void stop() {
if(lifeThread != null)
lifeThread.yield();
lifeThread = null;
//run method
public void run() {
while (lifeThread!=null) {
next();
gen_num++;
repaint();
try {
lifeThread.sleep( delay );
} catch (InterruptedException e){}

no.....thread.stop() is not a good read for your question....ignore the last poster.
You have the right idea...you simply need to set your boolean in a finer grained way. If you are in a long loop, then you should be checking that boolean value at the top of your loop so you can drop out of the loop immediately when the user requests to stop it.
So again, right idea, you just need a minor logic change.

Similar Messages

  • Stopping thread with timeout using threadpool

    Is there any way to set thread timeout within Executor.newFixedThreadPool ? I have a long queue around 5M which is creating with:
    ExecutorService executor = Executors.newFixedThreadPool(500);
    total = 10000;
    while (totalRows > 0) {
                    localStatement.executeQuery("SELECT domainID, domain FROM com WHERE status = '' LIMIT " + total);
                    totalRows -= total;
                    localResultSet = localStatement.getResultSet();
                    while (localResultSet.next()) {
                        HttpGet httpget = new HttpGet("http://" + localResultSet.getString("domain").toLowerCase());
                        executor.submit(new GetThread(httpClient, httpget, localResultSet.getInt("domainID")));
                    Thread.sleep(1000);
                    while (((ThreadPoolExecutor) executor).getActiveCount() > 10) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                    localResultSet.close();
                    System.out.println("New cycle");
                }But sometimes threads lock and cycle can't finish. Is there anyway to stop thread after N seconds? I can encapsulate Runnable into another Runnable and stop it from there, but it doubles threads, and I believe its not a good way.

    yes, you need at least one more thread. you could use one thread to monitor multiple other threads, but you need at least one more thread to wake up after the timeout and check on/cancel the main task.

  • Cannot Stop Thread with ServerSocket

    Hi
    I have a problem with a Thread that runs a ServerSocket. I want to stop this Thread from the main-application:
    Thread class:
    Constructor:
    serverSocket = new ServerSocket(address, port);
    public void run() {...
    while (true) { ....
    clientSocket = serverSocket.accept();
    I want to do the following in the main-application:
    because I want to set up a Thread with a new ServerSocket:
    myThread = null; // to stop the Thread, I also have tried to interrupt without success
    myThread = new Thread(); // => BindException and serverSocket == null;
    I always catch a BindException and in the Thread-Constructor the serverSocket is set null !
    How can I avoid this?
    I need to get a new serverSocket!!
    Can anyone help me?
    thanks, walter

    Thank's for reply: The problem I have is the following: My domain has a dynamic IP, so after the IP changes the s.accept() does not work any more!
    try // Point 1 *)
    ServerSocket s = new ServerSocket(portNumber);
    for(;;)     
    Socket incoming = s.accept(); // does not work after IP changes
    new ThreadedEchoHandler(incoming, i).start();
    So I have to detect that the IP has changed and have to start again at Point 1
    How can I do this?
    thx walter

  • How to stop thread permanatly after start?

    hello,
    i am using one thread . that thread start with time delay 10 seconds as follow,
    class tableUpdateThread implements Runnable
        Thread thread;
        int i,j;
        tableUpdateThread()
            thread = new Thread (this, "Table updation");
            thread.start();
        public void run()
            System.out.println (" Update thread starts........");
    try
                      System.out.println (" Update thread starts 4........");
                      Thread.sleep(10000);
                  } catch(InterruptedException ee)
                      System.out.println ("");
    }but, in one point in program, i stopped the thread by,
    tableUpdateThread.thread.stop();but, the thread again started after 10 seconds.
    Whhen I go to another panel, I need to stop the thread permanatly.
    But, in panel 1 I need the thread update the JTable every 10 seconds.
    but in panel 2 I need to stop the thread completely.
    how can I do it.
    please help me.

    Thread.stop has been depracated as unsafe.
    The legitimate way for a thread to stop is for it to return from the run() method.
    Typically you do this by interrupting the thread. If the thread is in sleep or wait this will trigger an InterruptedException. If not, it sets a flag, which the thread should check when it does a loop.
    (If a thread calls sleep or wait after being interrupted, it throws InterruptedException immediately.)

  • How to stop thread ?

    Hi all,
    Could you tell me pls, how to stop a thread ?
    thanks in advance
    bye

    Well, there is a stop method on the Thread class, but its been deprecated, and its not a good idea to use it. The reason is that you might call stop when your code is in a criticial section (ex. in a sync block).
    The best way is to have a method on your class that takes a boolean timeToDie and stores it in an instance variable. timeToDie should start out false. Have your thread check the boolean once in a while and if it ever turns to true then exit your thread appropriately.
    That should do it. Good luck!

  • Stopping thread in between

    Hi Guys,
    In my run() method, I am making a call to a method from an object provided by third party...now sometimes it just takes forever for that method to return the response back and we have to impose restriction to abort it if it is taking more than some amount of time. I tried to read some documents but most of the time they suggest stopping run method in between somewhere but not actually terminating when it is waiting for some method to return the response. To give you more detail I have something like this..
    public void run() {
       callNavigator();
    void callNavigator() {
       thirdPApi.makeCall()    //and here sometimes it waits forever to get the response back
    }and in another class I am doing xyzThread.start(); How can I impose time restriction and if thread is not done with the task then stop/destroy it? Somewhere I read if I do Thread.join(milliseconds), it will wait for run method to finish upto milliseconds . But doesnt say would it totally terminate the thread and release locks or what would it do.
    Can anyone suggest solution?

    destroy method is not implementable. And my problem is it is waiting at one point for response from the API method and I really dont know how to somehow get it break out of it. What if I do xyzThread.join(milliseconds) ... what would happen if after number of milliseconds thread is running? Documentation says that it waits for that number of milliseconds for run to finish but what after that?
    why dont you just put time restriction on the thread
    (i.e. system time or cpu time) after that time destroy
    the waiting thread.

  • Transaction timeout and never stopped thread

              Hi, joe:
              I noticed, if I make a transaction locked, whether I use OCI or JDRIVER, the thread
              will never stop after the transaction timed out. Only when I use OCI and use statement.setQueryTimeout,
              the thread will be stopped in 300 seconds. Is there any global operation to set
              such kind of properties?
              I did the testing on weblogic7.0 and I noticed that there's no such kind of problem
              in weblogic 8.1.
              Thanks&Regards
              

              lumin wrote:
              > Hi, Joseph:
              >
              > the weblogic version is 7.0 sp4
              >
              There is no way to ensure that Statement.setQueryTimeout() is
              called automatically. Note that it is an instance method on
              Statement, which your code creates. However, we do all we
              can to stop ongoing transactions that are being timed out. For instance,
              we do call Statement.cancel() on any statement your code is
              running at the time. We have found that certain CallableStatements
              and procedures in Oracle do not respond to the cancel(), so we are
              unable to reclaim the thread until the DBMS responds.
              Joe
              >
              > Joseph Weinstein <[email protected]> wrote:
              > >
              > >
              > >lumin wrote:
              > >
              > >> Hi, joe:
              > >>
              > >> I noticed, if I make a transaction locked, whether I use OCI or JDRIVER,
              > >the thread
              > >> will never stop after the transaction timed out. Only when I use OCI
              > >and use statement.setQueryTimeout,
              > >> the thread will be stopped in 300 seconds. Is there any global operation
              > >to set
              > >> such kind of properties?
              > >>
              > >> I did the testing on weblogic7.0 and I noticed that there's no such
              > >kind of problem
              > >> in weblogic 8.1.
              > >>
              > >> Thanks&Regards
              > >
              > >So things are OK in 8.1 but not in 7.0. What version of 7.0? Do try the
              > >latest sp.
              > >Joe
              > >
              > >
              

  • How to stop threads ???

    Dear all,
    I have a main class in which I declare and start 3 different threads, nothing else.
    When an event occurs in one of the threads, I would like to stop the 2 others and to finish my application ?
    How can I do that ?
    My Main:
    public class client_cc {
    public static Multicast_all multicast_all;
    public static Multicast_zone multicast_zone;
    public static Unicast unicast;
    public static void main(String arg[])
    String multicastall = null;
    int portall=0;
    String multicastzone = null;
    int portzone=0;
    try{
    String temp;
    FileInputStream sonInput = new FileInputStream ("server_config.txt");
    DataInputStream sonData = new DataInputStream (sonInput);
    while ((temp = sonData.readLine()) != null) {
    if(temp.equals("multicast_all")){
    multicastall = sonData.readLine();
    Double valeur = new Double(sonData.readLine());
    portall = valeur.intValue();
    if(temp.equals("multicast_zone")){
    multicastzone = sonData.readLine();
    Double valeur = new Double(sonData.readLine());
    portzone = valeur.intValue();
    sonInput.close();
    }catch(Exception e){}
    // I START THE THREADS
    multicast_all = new Multicast_all(multicastall, portall);
    multicast_all.start();
    multicast_zone = new Multicast_zone(multicastzone, portzone);
    multicast_zone.start();
    unicast = new Unicast();
    unicast.start();
    public static void stop(){
    unicast.stop();
    multicast_zone.stop();
    multicast_all.stop();
    ONE OF THE TREADS:
    public class Unicast extends Thread {
    public Runtime run = java.lang.Runtime.getRuntime();
    public Process proc;
    public Multicast_zone multicast_zone;
    public Multicast_all multicast_all;
    public Unicast() {
    public void run(){
    try{
    DatagramSocket s = new DatagramSocket(10000);
    byte[] buf = new byte[100];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while(true){
    s.receive(recv);
    String message = new String (recv.getData());
    Double valeur = new Double(message.substring(5, 9));
    int size = valeur.intValue();
    message = message.substring(9, size);
    System.out.println(message);
    if(message.equals("server_cpu_reboot ")){
    multicast_all.stop();
    multicast_zone.stop();
    try{
    proc = run.exec("./shutdown.exe -r");
    }catch(java.io.IOException e) {System.out.println(e);}
    stop();
    }catch(Exception e) {e.printStackTrace();}
    }

    Add the following line in ur code whereever u want ur thread to stop
    "STOP U ARROGANT THREAD"
    Simple isn't it?

  • Stop thread with error 1000

    Iam trying to start a thread by dynamically calling a re-entry vi and get a calling reference therefore. When I need to close the vi, I just use that vi reference to close it.
    But I got the Error 1000 LabVIEW:  The VI is not in a state compatible with this operation.
    Please see the attached piece code for the way I am open and close it(, since the original code is a bit complex)
    P.S.
    What is the best way to stop one of the multi dynamically called out re-entry vi outside itself somewhere else.
    Also if multi instances of one re-entry vi are called out, how to monitor their existing status in debugging, such as whether they been killed. The log file some time is a bit slow.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Open Close.vi ‏19 KB
    PubSub_QueueServiceTask.vi ‏22 KB
    PubSub_TCPServiceTask.vi ‏15 KB

    Hi,
    Even though the subVI that you called is running, it is not running under its own execution; it is part of the execution of the top-level VI. The execution of a VI depends on the execution of the subVI that is called, so you are not allowed to abort the execution of a subVI. Even though two parts of the main VI may be running in parallel (the subVI and the VI Server Abort command), the subVI is not executing on it's own; it is part of the caller VI.
    In order to abort a subVI from another VI, it needs to be running as a VI, not as a subVI. To make this happen, you would need to start the subVI through VI Server, using an Invoke node with the Run method. You also need to set the Wait until done option to False to eliminate the data dependencies of this VI. This way you can run and abort a VI from another VI. The major drawback to this however, is the greater difficulty of passing data values to the called VI. You would have to use the Set Control Value and Get Control Value methods to pass data to and from the called VI. I attached the examples below.
    Sincerely,
    Gunyapart Deephanphongs
    Application Engineer
    NI ASEAN
    Message Edited by Chongnang on 11-21-2008 03:22 AM
    Attachments:
    That.vi ‏11 KB
    This.vi ‏12 KB

  • Stop thread

    how to stop all the running threads

    hw to keep list and Just use a Vector, and put every thread in it when you start it.
    make thread stopableMake sure it never deadlocks, so no while(true), no IO read withou checking how much you can read, and that kind of stuff.

  • Stopping threads Urgent

    hi all,
    i have an application which forks out one or more threads.now if in between i need to save information and close down one thread what do i do.

    There are many ways to keep a reference to your Threads. You can use an array, a Collection, or in the code below, I hold a reference to the Threads in a DefaultListModel, which is used by a JList to show the Threads that are running.
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    public class App extends JFrame {
        public static int NUMBER_OF_PIPES = 5;
        private JList list;
        private DefaultListModel model = new DefaultListModel();
        public App() {
            this.list = new JList(this.model);
            JScrollPane scrollList = new JScrollPane(this.list);
            JButton startButton = new JButton("Start");
            JButton stopButton  = new JButton("Stop");
            this.getContentPane().setLayout(new FlowLayout());
            this.getContentPane().add(startButton);
            this.getContentPane().add(stopButton);
            this.getContentPane().add(scrollList);
            startButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    startPipelines();
            stopButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    stopSelectedPipelines();
        public void startPipelines() {
            for (int j = 0; j < NUMBER_OF_PIPES; j++) {
                Pipeline pipeline = new Pipeline("Pipe" + j);
                this.model.addElement(pipeline);
                pipeline.start();
        public void stopSelectedPipelines() {
            Object[] pipelines = this.list.getSelectedValues();
            for (int j = 0; j < pipelines.length; j++) {
                ((Thread) pipelines[j]).interrupt();
                this.model.removeElement(pipelines[j]);
        public static void main(String[] args) {
            JFrame app = new App();
            app.pack();
            app.setVisible(true);
            app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public class Pipeline extends Thread {
        private String name;
        public Pipeline(String n) {
            this.name = n;
        public void run() {
            while(!Thread.interrupted()) {
                try {
                    //do something here
                    System.out.println(this.name);
                    Thread.sleep(500); // or yield();
                } catch (InterruptedException e) {
                    this.interrupt();
        public String toString() {
            return this.name;
    }

  • Stopped threads waiting on DriverManager.getConnection()?

    Solaris 5.8, Sun JDK 1.3.1-b24
    RMI based application with the server piece running as a Java app on Solaris. After a few hours of use, with 100-150 users, the server app appears to hang from the client. If I do a kill -3 on the server process, I see a whole buttload of threads (over 100) stuck on DriverManager.getConnection() method (see below). The trace doesn't show anything deeper than that, but it is Oracle thin client being used. Our DBAs don't see any connections being attempted in the listeners log, and in fact, the number of the connections I see to the DB box via netstat jives exactly with the number of sessions I see on the Oracle side (in V$SESSION). While this is going on, I can connect to the DB box from the app server box all day long using a small class I wrote that just does a connection open and close.
    This app was working fairly flawlessly until about a week ago. Nothing in terms of drivers or JVM version has changed, but there has been slightly more user load lately. It seems that every new user request that comes in after a certain point ends up with a thread blocked like this. What is the thread stopped in getConnection() indicative of? Has anyone seen anything like this?
    Much appreciated,
    Mike
    Tons of these show in the thread dump (kill -3):
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:"RMI TCP Connection(11307)-10.160.96.220" daemon prio=5 tid=0x4946d0 nid=0x2e7b waiting for monitor entry [0xd4480000..0xd44819e0]
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at java.sql.DriverManager.getConnection(DriverManager.java:193)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at sched_MT.rmiSched_MTImpl.getLocation(rmiSched_MTImpl.java:556)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at java.lang.reflect.Method.invoke(Native Method)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:241)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at sun.rmi.transport.Transport$1.run(Transport.java:152)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at java.security.AccessController.doPrivileged(Native Method)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at sun.rmi.transport.Transport.serviceCall(Transport.java:148)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:465)
    Wed May 19 11:40:04 EDT 2004:ExecGroup-0:out:     at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:706)

    Yes - it is roughly 1 user : 1 DB connection. No pooling. Rogue app that we inherited. Ack. While it's blocking users, I can connect to the DBs fine (there are 2) from another app on the same box using the same DB logins and the same DBs, so my impression is that it's not DB related, but at this point, I am not completely sure about that. Our DBA says TNS is not getting any connect attempts during this time, so it seems like the driver is not even attempting.

  • How to stop threads, process, streams when closing a (internal) JFrame?

    Dear all,
    I read a Javaworld article about Runtime.exec(), which will output the process outputs and error outputs to either a file or System.out. Now I want to practice it by outputing the process output/error to a Swing JTextArea. It works fine if the process ends successfully.
    My problem is that I want to stop all the output threads and clear all the streams when user click close JFrame button before the process finished. The code is shown below. Note that this frame is poped up by a click from another main frame. ( it is not exiting the main Swing application). This happened when I want to kill a process when it is running.
    I tried to implements a WindowListener and add
    public void windowClosing(WindowEvent e) to the JFrame.
    Inside this method I used process.destroy() and errorGobbler = null, outputGobbler = null, or outputGobbler.interrupt(), errorGobbler.interrupt(). But all these seems does not work. Sometimes thread was not stopped, sometimes process was not destroyed (because the stream was still print out something), sometimes the error stream was not successfully closed - by printing out interruptted by user error message.
    How can I make sure all the underlying streams and threads, including the PrintStream in StreamGobbler class are closed?
    Again this Frame could be a Dialog or InternalFrame, i.e, when I close the frame, the main frame does not exit!
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        OutputStream os;
        StreamGobbler(InputStream is, String type, JTextArea out)
            this(is, type, null, out);
        StreamGobbler(InputStream is, String type, OutputStream redirect, JTextArea out)
            this.is = is;
            this.type = type;
            this.os = redirect;
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    if (pw != null)
                        pw.println(line);
                    out.append(type + ">" + line);   
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe)
                ioe.printStackTrace(); 
    public class Test extends JFrame
        private JTextArea output;
        private StreamGobbler outputGobbler;
        private StreamGobbler errorGobbler;
        public Test (String file)
            super();
            output = new JTextArea();
            try
                FileOutputStream fos = new FileOutputStream(file);
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java jecho 'Hello World'");
                errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR", out);           
                outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT", fos, out);
                errorGobbler.start();
                outputGobbler.start();
                int exitVal = proc.waitFor();
                output.append("ExitValue: " + exitVal);
                fos.flush();
                fos.close();       
            } catch (Throwable t)
                t.printStackTrace();
         setSize(400,400);
         show();
    }Thanks !

    Thread.interrupt() doesn't stop a thread. You'll have to read the API for more specifics. You could use something like interrupt to force interruption of the thread for the reason of checking the terminating case though. I believe you would want to use this in the case where operations can take a long time.
    Setting your reference to the thread to be null won't stop the thread since it's running. You just lose your reference to it.
    I believe once the thread stops running your streams will be closed, but possibly not cleanly. Someone who has more knowledge of threads might be able to answer this better, but I would generally say clean up after yourself especially if you are writting out data.

  • Reading char from keyboard to stop threads?

    I want to kill all the threads an terminate my program execution when I enter some char, for example 'S'.
    BUT, I dont want the execution flow to wait in the sentence 'prompt.read()' until I enter some character.
    does somebody knows the solution?
    this is my program:
    import java.io.*;
    public class Finalizadora extends Thread {
         public static boolean ejecucion = true;
         public void run() {
              while (ejecucion) {
                   try {
                        sleep(1000);
                   } catch (Exception e) {
                        // Si falla el sleep lo simulamos
                        for (int i = 0; i < 1000 * 10; i++) {
                        } // fin del for
                   } // fin del try
                   try {
                        BufferedReader prompt = new BufferedReader(new InputStreamReader (System.in));
                        if (prompt.read() == 'S') {
                            ejecucion = false;
                        } // fin del if
                   } catch (Exception e) {
                        System.out.println("SOME FAILS!!");
                   //System.out.println("--------------------");
              } // fin del while
              System.out.println("ENDING...");          
         } // fin de parsear
    } // fin de Finalizadorathanks!

    Hello.I cant read chars from a file.I am trying to fing to character with Max Occurrence in a file but when I run it it stops abruptly.This is my code.Can you help me please.Thank you
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * @author Dimitrios
    /*Assuming that the char with the max frequency in an standard English test is 'E' we can guess
    * that the char with the max frequency in the cipher text is E.This will
    * lead us to an approximation of the Key by shifting */
    import java.io.*;
    public class Frequency_Decprypt {
    public static int Occurrence(String str, char ch) {
    int occur=0;//the occurrence of char ch in the string
    for(int i=0;i<str.length();i++){
    if(str.charAt(i)==ch){
    occur++;
    return occur;
    public static char Frequency() throws IOException{
    BufferedReader in;
    FileReader fr;
    int key=0;
    char Max_FreqChar=' ';//the char with the max frequency
    int Max_Freq=0;// the max frequency of a char
    try{
    fr=new FileReader("Encrypted.txt");//the input file to read
    in=new BufferedReader(fr);
    //read a line from file
    String s=in.readLine();
    while(s!=null){
    for(int i=0;i<s.length();i++){
    if(Occurrence(s,s.charAt(i))>=Max_Freq){
    Max_Freq=Occurrence(s,s.charAt(i));
    Max_FreqChar=s.charAt(i);
    s=in.readLine();
    fr.close();
    //key=(int)('e'-Max_FreqChar);
    //key=Math.abs(key);
    } catch (FileNotFoundException e)
    { System.out.println("File not found");}
    return Max_FreqChar;
    }

  • Stop threads after a certain time

    I want to create a program that wants to do some work simultaneously, but each thread will return back after some time, however I do not want to wait forever so I want to stop all active threads after say 1 minute. Below is what I am doing but I am unable to stop the executing threads:
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(
    tpSize, tpSize, 5, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>());
    Task[] tasks = new Task[nTasks];
    for (int i = 0; i < nTasks; i++) {
    tasks[i] = new Task(n, "Task " + i);
    tpe.execute(tasks[i]);
    tpe.shutdown();
    System.out.println("Done!");
    try {
    tpe.awaitTermination(5, TimeUnit.MILLISECONDS);
    catch (Exception e) {e.printStackTrace();}
    class Task implements Runnable {
    long n;
    String id;
    private long fib(long n) {
    if (n == 0)
    return 0L;
    if (n == 1)
    return 1L;
    return fib(n - 1) + fib(n - 2);
    public Task(long n, String id) {
    this.n = n;
    this.id = id;
    public void run() {
    Date d = new Date();
    DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS");
    long startTime = System.currentTimeMillis();
    d.setTime(startTime);
    System.out.println("Starting task " + id + " at " + df.format(d));
    System.out.print("Fib: " + fib(n));
    long endTime = System.currentTimeMillis();
    d.setTime(endTime);
    System.out.println(" Ending task " + id + " at " + df.format(d) + " after " + (endTime - startTime) + " milliseconds");
    How come the threads do not stop especially when I have set a 5 Millisecond timeout?
    How do I go about stopping active threads?
    Message was edited by:
    dawuad

    I want to create a program that wants to do some work simultaneously, but each thread will return back after some time, however I do not want to wait forever so I want to stop all active threads after say 1 minute. Below is what I am doing but I am unable to stop the executing threads:
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(
    tpSize, tpSize, 5, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>());
    Task[] tasks = new Task[nTasks];
    for (int i = 0; i < nTasks; i++) {
    tasks = new Task(n, "Task " + i);
    tpe.execute(tasks);
    tpe.shutdown();
    System.out.println("Done!");
    try {
    tpe.awaitTermination(5, TimeUnit.MILLISECONDS);
    catch (Exception e) {e.printStackTrace();}
    class Task implements Runnable {
    long n;
    String id;
    private long fib(long n) {
    if (n == 0)
    return 0L;
    if (n == 1)
    return 1L;
    return fib(n - 1) + fib(n - 2);
    public Task(long n, String id) {
    this.n = n;
    this.id = id;
    public void run() {
    Date d = new Date();
    DateFormat df = new SimpleDateFormat("HH:mm:ss:SSS");
    long startTime = System.currentTimeMillis();
    d.setTime(startTime);
    System.out.println("Starting task " + id + " at " + df.format(d));
    System.out.print("Fib: " + fib(n));
    long endTime = System.currentTimeMillis();
    d.setTime(endTime);
    System.out.println(" Ending task " + id + " at " + df.format(d) + " after " + (endTime - startTime) + " milliseconds");
    How come the threads do not stop especially when I have set a 5 Millisecond timeout?
    How do I go about stopping active threads?
    Is ThreadPoolExecutor right for me?

Maybe you are looking for