Stop a running thread

I create a thread and while it is running i want to stop it but not wait what should i do to solve this problem.
Edited by: phamthao on May 24, 2009 12:13 PM

public class Example implements Runnable{
     private boolean isRunning, MISTAKE;
          isRunning = true;
          MISTAKE = false;
          Thread thread = new Thread(this);
          thread.start();
     public void run(){
          while(isRunning){
               //do stuff
               if (MISTAKE){
                    isRunning = false;
}Pretty general

Similar Messages

  • Stop the running Thread

    Hi
    i am calling the thread .in the midlle of running thread i have to stop the thread .please help me .
    my senario like . I am calling the scripts . i am wating certain period to complete the script exection . if the scripts are not available its still wating for a long time . so i am using the thread to execute the scripts and (main thread )checking each duration is completed or not . if the duration completed i am stoping the thread with Thread.Stop() method . but the thread still is alive . next time when i call Thread.Start() its throwing "java.lang.IllegalThreadStateException".
    please help me this .
    Thanks in advance
    public class TestCaseScriptProcessor extends Thread {
    public String execute(){
    TestCaseScriptProcessor caseScriptProcessor = new TestCaseScriptProcessor();
    caseScriptProcessor .start();// second time throwing java.lang.IllegalThreadStateException.
    while (!isExpired) {
    caseScriptProcessor.stop();
    public void run() {
    Edited by: 849614 on Jan 17, 2013 6:17 AM
    Edited by: 849614 on Jan 17, 2013 6:22 AM

    What exactly are you trying to do? Calling Thread.stop( ) is inherently a bad idea (see the Javadocs).
    You are getting a IllegalStateException because Thread.stop( ) kills the thread, you would need to create a new thread to resume execution.
    If what you are trying to do is pause execution, you probably want to redesign your thread's tasks into smaller chunks that can be launched separately. Alternatively, have the thread check it's interrupted state and if a flag was set block on a monitor until you want it to resume execution.

  • Running thread behaviour on calling interrupt?

    if a thread T1 is running and interrupt is called on this thread,there will be no impact on thread T1 processing/behaviour. To handle this
    we have to call if (Thread.interrupted()) inside run method of thread T1 right?
    Interrupt will have impact when thread is under wait,sleep or join(or methods that throw InterruptedException),Right?
    In above question , impact refers to the case when InterruptedException will be thrown.
    Asked the question at http://www.coderanch.com/t/545582/threads/java/Impact-interrupt-Running-thread but did not get satisfactory reply though i have been thru api doc.

    Interrupting a thread sets a flag for that thread. Setting that flag will cause some blocking operations to throw an exception. e.g. sleep, wait, NIO read. Unless you do one of those operations, setting the flag doesn't do anything which is a problem for those who hope to stop a running thread in an untrusted third party library. ;)

  • How to 'STOP' a running java thread in J2ME?

    Dear All,
    How to 'STOP' a running java thread in J2ME?
    In the middleware viewpoint, for some reasons we have to stopped/destroyed the running threads (we have no information how these applications designed).
    But in J2ME, Thread.destroy() is not implemented. Are there other approaches to solve this problem?
    Thanks in advance!
    Jason

    Hi jason,
    Actually there are no methods like stop() and interrupt() to stop the threads in J2ME which is present in normally J2SE Environment.
    But the interrupt method is introduced in Version 1.1 of the CLDC.
    So, we can handle the thread in two ways.
    a) If it is of single thread, then we can use a boolean variable in the run method to hadle it. so when the particular boolean value is changed , it will come out of the thread.
    for eg:
    public class exampleThread implements Runnable
    public boolean exit = false;
    public void run()
    while(!exit)
    #perform task(coding whatever u needed)
    public void exit()
    exit = true;
    b) If it is of many threads then we can handle using the instance of the current thread using currentThread() method
    for eg:
    public class exampleThread implements Runnable
    public Thread latest = null;
    public Thread restart()
    latest = new Thread(this);
    latest.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while( latest == thisThread )
    #perform some tasks(coding part);
    public voi d stopAll()
    latest = null;
    while ( latest == thisThread )
    performOperation1();
    if( latest != thisThread )
    break;
    performOperation2();
    Regards,
    Prathesh Santh.

  • How to stop the running infospoke

    Hi Experts,
    there is a infospoke is still running so long time, it's incorrect, i'll cancel it as kick off the dependenies, i have no idea to how to stop the running infospoke. Anybody could tell me how to do it. thanks in advance.

    hi denny,
       Go to SM37 , find the job , stop the process
    or
       To stop the job find the job with the help of the request name ( TC - SM37 ),then in the job Details find the PID .
    find the process in the process Overview (SM50 / SM51 ).
    Set the restart to NO and Cancel the process without core
    u can also see these threads that are already posted:
    stopping v3 run job LIS-BW-VB_APPLICATION_02_010
    how to cancel or change the background job which is scheduled
      In SM37, for the job , click on Step button. Then from the menu Goto > variant. You can see the process chain name here.
    sure it helps
    Thanks
    Varun CN

  • How to stop a running process

    If I have a class
    class MyTest{
    public void start(){
    int count=0;
    while(true)
    System.out.println(count);
    ++ count;
    class TestRun{
    public static void main(String[] args)
    MyTest test = new MyTest();
    test.start();
    My question is is there a programatic way to stop MyTest counting in TestRun ? except of course by assigning it a null value;

    First of all what you have is not a process -- it's a thread. Separate processes each have their own memory, but threads share the memory with the other threads in the process.
    Second, I don't see any reference that you could set to null to stop the thread. Were you thinking of setting your local reference to the thread to null? That will only set that particular reference to null, and will not affect the thread.
    You could call stop() on the thread to stop it, but doing so is unsafe.
    The best solution is for the thread to continually check some flag to determine if it should keep running. The loop should continue only while that flag is true.

  • Stopping a Running process in EPMA workspace.

    Anyone?
    I have about a dozen running process that are sitting idle. How can i stop them? this is production environment. I've restarted all the services, still there shows running. any solutions besides rebooting the server?
    Most of the process are HFM Re-deploy and export.
    Any solutions?
    Regards,
    Alex Mathew

    Hi, I'm been unable to kill a running/executing thread. Here's how I created the thread:
    EvoluteRun er = new evolutionary.EvoluteRun();
    Thread t1 = new Thread(er);
    then here's how I'm trying to kill the executing thread:
    private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {
    if ( (t1 != null) && (t1.isAlive()) ) {
    System.out.println("going to suspend");
    t1.suspend();
    System.out.println("stop");
    To my amazement, the stop printouts only comes up after the running thread had been finished (finished the run()) althogh the stop button had been clicked (many times as well), there seems no effect no the executing thead. Please help.
    Thanks

  • Cannot stop memory monitor thread

    Hi All,
    I am getting the following error intermittently in a dataflow which has degree of parallelism = 8.
    22943 0 SYS-170111 27/11/2009 12:22:05 |SubDataflow DF_Conform_ISI_Person_Match_Prep_1_9
    22943 0 SYS-170111 27/11/2009 12:22:05 Cannot stop memory monitor thread: <RWThreadImp::terminate - No thread is active within the runnable>
    Any ideas as to the cause ?
    Thanks,
    Eric Jones.

    We are having the same issue.
    According to ADAPT00890818, this issue should be resolved in 12.0.0. We are currently running with version 12.2.2.3.
    Please advice.

  • Long running threads.

    Hello everyone,
    Thanks for your interest in this post. I have a design question on a feature we are currently working on - I have described it below as best as I can. I would be thankful for any direction or guidance from all the good and experienced folks here in this forum :)
    We have a system which receives some input data (say in the form of files or a db update) from external sources. We have a job which wakes up periodically, checks for the presence of new data and then does some parsing/data manipulation. I have posted it below and for the sake of brevity and conciseness kept it simple.
    public class Work{  
        private SomeVar _var;  
        //constructor here  
        public void doWork(){  
             //run job  
    }  Note we have multiple kind of input (so multiple Work classes each of which have different parse logic).
    So far so good.
    We have jdk 1.4 (no java.util.concurrent) and we dont have an option to use a scheduling f/w like quartz
    Its simple enough and we dont have a need for Listeners, dynamic scheduling etc.
    That leaves us with 2 options to implement this
    Option 1
    Create a thread for each kind of job on startup.
    Each thread checks for presence of input data and creates a Work object to process the job.
    public class WorkThread extends Thread{//some common functionality here}
    public class SpecificWorkThread extends WorkThread{  
           private MetaInfo _meta;  
           //constructor  
           public void run(){  
              while(true){  
                    //check for presence of input data  
                    Work _w = new Work();  
                    _w.doWork();  
                    //sleep for some time  
    pulic class Controller{
          psv main(String args[]){
         //for each job{
                 WorkThread t = new SpecificWorkThread();
                 t.start();
             //join on all threads
    }  As you can see this would create (from the main), a long running thread for each job type
    Option 2
    Have the input data check in the controller clas. When there is input data to parse, create a Thread which does the parsing.
    The thread in its run method parses and comes out. So for each parse cycle, a short lived thread is created, somthing like below
    public class WorkController{  
           psv main(String args[]){  
                   while(true){  
                      //check for input condition  
                      new SpecificWorkThread(new Work()).start();  
                     //sleep for sometime  
              public class SpecificWorkThread extends Thread{  
                  private Work _work;  
                  //constructor  
                  public void run(){  
                        _work.doWork();  
            The difference between the two is that while the first creates long running threads per job type, in option(2) a thread is created on demand. Each thread is short lived (it does its job and dies), but then a thread needs to be created every time for a job.
    Both would work and work correctly. What I would like to understand is if the options presented above just a programmer's prefence or is one option better than the other (performance, memory considerations) etc?
    Thanks for your patience in reading this post.
    cheers,
    ram.

    Generally creating a new thread is an expensive process. Well, everything is relative. My laptop can create & run & stop 7,000+ threads per second, test program below, YMMV. If you are dealing with thousands of thread creations per second, pooling may be sensible; if not, premature optimization is the root of all evil, etc.
    public class ThreadSpeed
        public static void main(String args[])
         throws Exception
            System.out.println("Ignore the first few timings.");
            System.out.println("They may include Hotspot compilation time.");
            System.out.println("I hope you are running me with \"java -server\"!");
         for (int n = 0; n < 5; n++)
             doit();
            System.out.println("Did you run me with \"java -server\"?  You should!");
        public static void doit()
         throws Exception
            long start = System.currentTimeMillis();
            for (int n = 0; n < 10000; n++) {
             Thread thread = new Thread(new MyRunnable());
             thread.start();
             thread.join();
            long end = System.currentTimeMillis();
            System.out.println("thread time " + (end - start) + " ms");
        static class MyRunnable
         implements Runnable
         public void run()
    }Edited by: sjasja on Jan 14, 2010 2:20 AM

  • How to close all running threads

    I have many threads running everywhere in my application. when i disconnect from server, all sockets between me and the server must disconnect. but since different threads are having a socket connection each to the server, i cant close them all, since i dont have the reference to the diff thread objects.
    how do i close these sockets (each whole thread) ?
    Regards,
    Sid

    Thanks for replying.
    but i figured out the way last night itself.
    i was trying to fire a text changed event and putting a listener for it in every running thread so that when i want to disconenct, i would write some text into the textbox which would fire the event and the threads would listen to itr and kill themselves. but it simply wasnt workin.
    then i came across the class ThreadGroup. add each thread to that threadgroup adn say ThreadGroup.stop();
    Thanks anyway.
    Regards,
    Sid

  • Creating exception in a running thread

    what are the various way i can create an exception inside a running thread. (without using any Thread's interuption method) ? i want to interupt my thread . what are the ways ?

    PS If you mean you want to STOP the thread using an exception that will occur while it's running then - don't do that. The appropriate way to kill such a thread is to set a flag which your run method checks to determine if it should exit.
    D.

  • Stopping a "run-away" request

    What is the best way to stop a "run-away" request from a JSP? Say the User has a page from which he can issue a request. For example, say that the request performs a database query and returns a list of objects. If the system performance is slow, and the User is tired of waiting for a response, how may the applicaiton be designed to terminate a request to permit the User to issue a new request that is more granular and refined in its scope, and which will presumably run more quickly? Can one place a stop button on the form? Are there any threading issues in terms of the functionality with the stop button to be able to terminate the previous request that is "in-flight" with respect to the middle tier or the host?
    Does killing the browser session (which causes the client to lose connectivity to the middle-tier) automatically stop the request?
    Does pressing the stop button in the browser have the same effect?

    We are running the JSP in an IFrame within the browser, and I have noticed that pressing the browser's stop button has no effect on the JSP.
    Even if we could get this to work, I am not sure if it will cause the process on the middle-tier to stop consuming resources.
    Thanks for your feedback. I guess I am interested in learning about any/all implementation alternitives, with a view to understanding the complexity/cost/and limitations of each implementation alternative.

  • How do I STOP & DESTROY a thread?????

    I cannot seem to get my wait cursor to work. Sometimes it appears, sometimes it doesn't. After searching the forums I saw that I must put my long computational code in a seperate thread to get my wait cursor to be painted...
    My question is: How do you stop & destroy a thread? Or will it automatically stop/destroy itself when done running?

    Currently, what I am doing is:
    //set cursor
    public void run() {
    //long process
    //set cursor to normal
    This seems to work fine, but I just wanted to make sure there is not stop/destory method. I didn't want 50 empty thread floating around. I am new to using threads...
    Thanks!

  • Long running threads (Jasper Reports) and AM-Pooling

    Hi,
    we are developing quite large application with ADF an BC. We have quite a lot of reports generated through Jasper that take quite long time to complete. The result is a PDF document that user gets on the UI so he can download it over download link. Reports that take over an hour to finish are never completed and returned to the user on UI. I think the problem is in AM-Polling because we are using default AM-Polling settings:
    <AM-Pooling jbo.ampool.maxinactiveage="600000" jbo.ampool.monitorsleepinterval="600000" jbo.ampool.timetolive="3600000"/>
    The AM is destroyed or returned to pool before reports finishes. How to properly configure those settings that even long running threads will do there jobs to the end.
    We also modified web.xml as follows:
      <session-config>
        <session-timeout>300</session-timeout>
      </session-config>
    Any help appreciated.
    Regards, Tadej

    Your problem is not related to ADF ApplicationModules. AMs are returned to the pool no earlier than the end of request, so for sure they are not destroyed by the framework while the report is running. The AM timeout settings you are referring to are applicable only to idle AMs in the pool but not to AMs that have been checked out and used by some active request.
    If you are using MS Internet Explorer, then most probably your problem is related to the IE's ReceiveTimeout setting, which defines a timeout for receiving a response from the server. I have had such problems with long running requests (involving DB processing running for more than 1 hour) and solved my problem by increasing this timeout. By default this timeout is as follows:
    IE4 - 5 minutes
    IE5, 6, 7, 8 - 60 minutes
    I cannot find what the default value is for IE9 and IE10, but some people claim it is only 10 seconds, although this information does not sound reasonable and reliable! Anyway, the real value is hardly greater than 60 minutes.
    You should increase the ReceiveTimeout registry value to an appropriate value (greater than the time necessary for your report to complete). Follow the instructions of MS Support here:
    Internet Explorer error &quot;connection timed out&quot; when server does not respond
    I have searched Internet for similar timeout settings for Google Chrome and Mozilla Firefox, but I have not found anything, so I instructed my customers (who execute long-running DB processing) to configure and use IE for these requests.
    Dimitar

  • How to stop a running job in 10g Scheduler?

    The following is a duplicate post. I posted the following to the general database forum before seeing that otn has a new scheduler forum:
    I am not able to find in the Admin Guide a method to stop a currently running instance of a job in the 10g scheduler.
    In 9i, I run the following script calling DBMS_JOB.broken and DBMS_JOB.remove to shut down currently running jobs:
    DECLARE
    jobid NUMBER;
    CURSOR c1
    IS
    SELECT job
    FROM dba_jobs
    WHERE priv_user = 'ME';
    BEGIN
    OPEN c1;
    LOOP
    FETCH c1
    INTO jobid;
    EXIT WHEN c1%NOTFOUND;
    DBMS_JOB.broken (jobid, TRUE);
    COMMIT;
    DBMS_JOB.remove (jobid);
    COMMIT;
    END LOOP;
    CLOSE c1;
    END;
    How may I create similar code to shut down currently running jobs using DBMS_SCHEDULER in 10g? According to the Admin Guide, disabling jobs with the force option will still allow the job to finish.
    How can I terminate a running job in 10g?

    You can stop a currently running job using the STOP_JOB api.
    STOP_JOB Procedure
    This procedure stops currently running jobs or all jobs in a job class. Any instance of the job will be stopped. After stopping the job, the state of a one-time job will be set to SUCCEEDED whereas the state of a repeating job will be set to SCHEDULED or COMPLETED depending on whether the next run of the job is scheduled.
    Syntax
    DBMS_SCHEDULER.STOP_JOB (
    job_name IN VARCHAR2
    force IN BOOLEAN DEFAULT FALSE);
    Parameters
    Table 83-44 STOP_JOB Procedure Parameters
    Parameter Description
    job_name
    The name of the job or job class. Can be a comma-delimited list. For a job class, the SYS schema should be specified.
    If the name of a job class is specified, the jobs that belong to that job class are stopped. The job class is not affected by this call.
    force
    If force is set to FALSE, the Scheduler tries to gracefully stop the job using an interrupt mechanism. This method gives control back to the slave process, which can update the status of the job in the job queue to stopped. If this fails, an error is returned.
    If force is set to TRUE, the Scheduler will immediately terminate the job slave. Oracle recommends that STOP_JOB with force set to TRUE be used only after a STOP_JOB with force set to FALSE has failed.
    Use of the force option requires the MANAGE SCHEDULER system privilege.
    Setting force to TRUE is not supported for jobs of type executable.
    Usage Notes
    STOP_JOB without the force option requires that you be the owner of the job or have ALTER privileges on that job. You can also stop a job if you have the CREATE ANY JOB or MANAGE SCHEDULER privilege.
    STOP_JOB with the force option requires that have the MANAGE SCHEDULER privilege.

Maybe you are looking for

  • How to get the IP address of smtp server?

    For A record in DNS, we can use Java API InetAddress.getHostAddress() to get the IP address. But for mx record, how to get the IPaddress?

  • Oracle NoSQL and indexing

    Hi all, I read that there is an index on key value on each node. Does that mean that as soon as we have the good key, there is a full scan on all the values for that key on that node? So to have better performance should we have many keys and fewer v

  • Problem loading interclient Driver

    Hello, I have a problem with connection to interbase using jdbc : I try to do like this : try{ class.forname("interbase.interclient.Driver"); }catch (ClassNotFoundException e){System.out.println(e.getMessage());} but allways the compilator show error

  • Ipod classic got wet several months ago.

    It now displays a red X. Is it dead or is there something else I can do? (plugging in to computer doesn't do anything.)

  • Time Machine Backup and iPhoto

    I have backed up my iMac onto an external hard drive via time machine. I want to transfer my photos from iphoto onto my macbook pro. I already transfered my music by plugging the hard drive into my macbook, opening the hard drive folder, opening the