Stopping a thread from running

Hai
     I am new to java. It would be helpful for me if someone helps me out in doing this.
     Actually in my program ,I should
i. Find out whether a particular file exists in the given directory or not.
ii. If the file doesn't exist, my program should wait for certain timeframe and check for the same file again.
iii. If the program cannot find the required file within the timeout specified, my application should exit.
     I have done (i) and (ii) using threads. But in the case of (iii), I came to know that stop() method is depricated.
     I am providing my code for a better understanding. Could you please let me know, what would be the best way to stop the thread from running after the timeout is reached in my program?
Thanx in advance
import java.io.File;
public class Fileexists implements Runnable
static Thread t;
public static void main(String[] args)
     System.out.println("creation of object");     
     FileExists test = new FileExists();
     t = new Thread(test);
     t.start();
// run method
public void run()
     File f = new File("searchfile.txt");
     boolean b = f.exists();
System.out.println();
if(b == false)
System.out.println("Required file doesnot exists");
try
     t.sleep(20000);
catch (InterruptedException e)
     // TODO Auto-generated catch block
     e.printStackTrace();
          t.run();
else
System.out.println("Required file found");
} // end of run()
} // end of FileExists class

Actually your use of threads is a difference which makes no difference. The JVM starts an initial thread and runs your main(), at the end of which you start a thread and return. So you've just replaced one thread with another. There's no parallel processing.
The t.run() at the end of your run() method won't work. A particular Thread object can only run once. It will give you an IllegalStateException.
I can't see how multi-threading will help you with this task at all, all you need is a simple loop with a Thread.sleep in it.
If you really want to use a separate thread or Timer to implement a timeout (as an exercise) then use Thread.interrupt() to wind up a thread. The looping thread should test with Thread.interrupted() in it's loop condition, if it's in sleep() when interrupted an InterruptedException will be thrown which you should catch and allow to break the loop and let the thread terminate.
So your loop structure looks like:
try {
while(!Thread.interrupted()) {
    ...  do your test
    Thread.sleep(.....);
  System.out.println("Thread terminated by detecting interrupted");
  } catch(InterruptedException ex)  {
     System.out.println("Thread interrupted from sleep");
You can get the Thread for the main thread simply by storing Thread.currentThread() in a Thread reference.
I'd suggest using a java.util.Timer to launch your time-out and leave the loop on the main thread started by the JVM.

Similar Messages

  • Stop Oracle.exe from running in background?

    Hi,
    Since I installed Oracle 8i Personal Edition for Win 2000 (SP1), I have seen a great slowdown of my computer. It now takes much longer to start up Windows, longer to open applications and games (UT),.. I check Task Manger and see that Oracle.exe is consuming about 84 MB of my computer memory.
    Can someone help me stop Oracle.exe from running like this?
    Thanks a lot in advance
    Trung.

    Check Your services and set all related to Oracle to manual startup
    If You need Oracle, You will manually start these processes

  • How can I stop my battery from running out in my in my iphone 5 with the new i0s7

    how can I stop my battery from running at a super fast rate on my in my iphone 5 with the new i0s7, ever since I upgraded I am needing to charge up at least 3 times a day.

    https://discussions.apple.com/message/23361957#23361957

  • Stopping a thread from "cancel" button

    Hello all,
    I have a problem trying to stop a thread. I have a class that hits database and retrieves lots of data. This retrieval can take a long time if lots of data, so I have a progress bar displayed. This progress bar has a cancel button. I am not sure how to link the cancel button to the thread so the thread can exit. See code below for example of whats going on:
    public class MainApp {
      public void doWork() {
        ProgressBar pbar = new ProgressBar();
        pbar.show();
        DatabaseThread dbThread = new DatabaseThread();
        dbThread.run();
    public class ProgressBar {
      // displays a progress bar with cancel button
    public class DatabaseThread extends Thread {
      public void run() {
        // hit database
    }So how am I to cancel the DatabaseThread class from the ProgressBar class. Thanks for all suggestions!

    what i said is that you need to hava a reference to your thread ine the class that handle the progressBar.
    and in your Thread class you create a method like setCanceled(boolean b)...
    public MyThread extends Thread{
       private boolean canceled = false;
       public void setCanceled(boolean b){
          canceled = b;
       public void run(){
          while(!canceled){
            //do your stuff

  • Best way for a user to stop a program from running - B1 V8.8

    Hi
    I have written some import routines for a customer which import invoices and other documents into SAP from an ascii file
    These can take some time to run depending on the size of the file
    What's the best way of allowing the user to cancel the program ?
    I have tried adding application.doevents but it doesn't seem to help when I try clicking on the cancel button on the form
    Thanks for any ideas
    Regards Andy

    Hello Andy,
    1.st Use transacation to roll back when user presses the Cancel Button
    2.nd You may run the import file in a different thread from the addon, with a static global marker that the import must be cancelled or not
    3. Rigth now, because of a different thread, the addon will keep alive and wait for the cancel button event.
    4. when cancel button event raises, you send join into the separated thread, and stop it (eg cancel the thread).
    5. You can rollback the transactions done by the thread.
    I think you must do a multi threaded addon to handle this case.
    Regards
    János

  • I need an app that stops background apps from running when phone is sleeping

    i need and app that stops background apps (or maybe all apps) from running when phone is sleeping. thx!

    Too bad.  When I had a Droid there was an app that you could set which apps to quit and which to leave running.  Just convenient rather than having to go through the apps bar repeatedly and quit apps individually.  It is not an intrusion to control the phone or quit other running apps... it's my choice... Ooops!  My mistake.  Forgot that I no longer have free will in what I do.  The Company knows better.

  • How can I permanently stop Backup Asisstant from running in the background?

    Backup Asisstant plus is constantly running in the background of my phone. It is annoying and I can not even open it up under the "manage accounts" section of my phone. When I do this it just has the blue circle spinning forever and ever never openning up at all. Is there a way to fix this or am I just stuck battling this stupid app day after day. It came with the Verizon phone, but I had this before and customer service was able to stop it from running all the time. Now I get told there is nothing Verizon can do. So how can I stop this app permanently and why is there so much comflicting information coming from Verizon agents and its website? I cant seem to get a solid answer.

    I have a galaxy s3. The backup assistant just freezes my phone. It is always running in the background draining memory from my phone slowing it down. It is beyond annoying since even after a hard reset I can not even access the Backup Assistant + to manually change settings, so I would just like it to stay off. It has not helped me recover much in the way it was advertised.

  • How do I stop a query from running when the page is loaded

    Hi All,
    I'm using JDeveloper 10.1.3.4. I have a JSPX page that is used to collect search parameters and then when a button is clicked uses those values to run a query and then populate a table on the same page. The problem is that when the page is loaded the system attempts to run the query. The query is a method in a session bean. I can keep the method from running the query code by wrapping it in an 'if' statement and checking the parameters for null (or other value). Once the parameters are collected the query is invoked but it looks like the method is running twice, once with the parameters (here I've checked that the result actually has rows in the list) and then again where the parameters are null and the method returns null.
    What is the best way to do what I want here? From the buttons action method I am called the session beam method and returning null to stay on the same page. I think that is why the method is running the second time and returning null.
    TIA,
    Dave

    Have a look at these screen casts from Steve Muench and see if one of these techniques works for you, or gives you the clue you need.
    Creating Three Simple Search Pages with ADF Business Components and ADF Faces (JSF)
    Part 1: Web-Style Search Form
    Part 2: Oracle Forms-Style EnterQuery/ExecuteQuery Mode Page
    Part 3: Search Form Using View Object with Named Bind Parameters
    I had trouble viewing these with Firefox, but they worked in Internet Explorer.

  • Stop analyze.exe from running

    I am running ZCM 10.3. One workstation with ZCM agent installed kept getting error running analyze.exe and crashed her XP PC. I like to disable analyze from running as I only have a few PCs with the ZCM agent installed and I plan to build a new ZCM 11 server and roll out ZCM 11 as a new system.
    Login to ZCC but couldn't find the option to disable the scan....
    Any suggestion would be appreciated.
    Wilson

    Wilsonhandy,
    disable ZPM? With 10.3.3/11.1 you have the option to schedule the DAU,
    but otherwise it's going to run each day...
    Shaun Pond

  • How to stop as files from running until a certain frame

    Hi all,
    I have a simple flash game with two frames at the moment.
    Most of the stuff that happens is in as files linked to
    different movie clips.
    I orignially only had one frame my background frame and when
    testing I just press ctl+enter and bamm away it goes the
    actionscript runs as soon as the movie/game starts and ergo the
    game plays.
    My problem is this, I now want to have a start/home frame at
    the beginning (of course) which has the start game button on which
    when clicked THEN starts the game.
    Currently the game starts in the first frame along with the
    start button :(
    How do I stop the game running straight away and my first
    frame only contains the start button, which when clicked then goes
    to the 2nd frame and starts the game?
    Reagrds,
    Red.

    A friend resolved the issue for me;
    By renaming the main contrustor and calling this in the start
    button Example action script applied to the button:
    START OF ACTION SCRIPT
    import flash.events.MouseEvent;
    stop();
    startBTN.addEventListener(MouseEvent.CLICK, startClick);
    function startClick(event:MouseEvent):void
    trace ("Button clicked");
    gotoAndStop(2);
    gameGo();
    /*gameGo() is the renamed main document class, renaming it
    prevents it from been run instanly
    and it is called from the button*/
    END OF ACTION SCRIPT

  • How do I stop unnecessary programs from running in the background on a Macbook Pro 2010?

    Hi recently I bought a Macbook Pro OSX 10.8.3 2010 (2.4 GHz Intel Core / 2GB 1067 MHz DDR3). Im pretty content with it considering its my first Mac. Up until recently I had no problems with its speed.
    My brother directed me to the activity monitor and showed me how to quit a program. However there are still a several running programs I do not recognize and/or do not use (such as photo stream, Calendar Agent, UserEventAgent, Notification Center, AppleSpell service, cfprefsd, talagent, xpcd, imagent, com.apple.dock.extra, fontd, loginwindow, SystemUIServer, tccd, usernoted etc etc etc UGH!! The list just goes on and on. There is a circular graph at the bottom in pir form highlighted with the colors green, red, blue and yellow indicating what is taking up space or speed? If I quit Safari a huge portion of the green is highlghted. but I can not seem to get it to fill the majority of the pie graph. I see there are all these running programs (most of which I do not use or recognize) but I cannot get them to quit even if I highlight it. How can I stop this? Quite frankly its so frustrating. Again I am new to Mac.
    Thanks
    marcel11

    First, back up all data immediately, as your boot drive might be failing.
    There are a few other possible causes of generalized slow performance that you can rule out easily.
    Reset the System Management Controller.
    If you have many image or video files on the Desktop with preview icons, move them to another folder.
    If applicable, uncheck all boxes in the iCloud preference pane.
    Disconnect all non-essential wired peripherals and remove aftermarket expansion cards, if any.
    Check your keychains in Keychain Access for excessively duplicated items.
    Boot into Recovery mode, launch Disk Utility, and run Repair Disk.
    Otherwise, take the steps below when you notice the problem.
    Step 1
    Launch the Activity Monitor application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Activity Monitor in the icon grid.
    Select the CPU tab of the Activity Monitor window.
    Select All Processes from the menu in the toolbar, if not already selected.
    Click the heading of the % CPU column in the process table to sort the entries by CPU usage. You may have to click it twice to get the highest value at the top. What is it, and what is the process? Also post the values for % User, % System, and % Idle at the bottom of the window.
    Select the System Memory tab. What values are shown in the bottom part of the window for Page outs and Swap used?
    Next, select the Disk Activity tab. Post the approximate values shown for Reads in/sec and Writes out/sec (not Reads in and Writes out.)
    Step 2
    If you have more than one user account, you must be logged in as an administrator to carry out this step.
    Launch the Console application in the same way you launched Activity Monitor. Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left. If you don't see that menu, select
    View ▹ Show Log List
    from the menu bar.
    Select the 50 or so most recent entries in the log. Copy them to the Clipboard (command-C). Paste into a reply to this message (command-V). You're looking for entries at the end of the log, not at the beginning.
    When posting a log extract, be selective. Don't post more than is requested.
    Please do not indiscriminately dump thousands of lines from the log into this discussion.
    Important: Some personal information, such as your name, may appear in the log. Anonymize before posting. That should be easy to do if your extract is not too long.

  • Stop jrun.exe from running

    Hi guys anf girls,
    My computer has been running pretty slow, so i did the
    obvious and checked out the window task manager. There i had seen
    an application "jrun.exe" eating a large chunk from my computers
    processing power.
    I had googled it to find out what it is, and I now know its
    from my coldfusion installation, a server. I done my research to
    see how to stop this, where by opening up jrun.exe and stopping it.
    The thing is, after i cancel it, it starts up again.
    Can anyone point me in the right direction in how to actually
    stop it and then manually start it. I have tried using the
    administrator page but i dont know where to go.
    I am using coldfusion 7, the latest developer edition.
    cheers
    Darren

    ColdFusion runs as a service on windows. Several services
    actually. The service names usually begin with ColdFusion MX 7. To
    start or stop the services, use control panel > services. Select
    each service, click properties then click stop or start.
    If you do not want ColdFusion to start automatically when the
    o/s boots, change the service properties from Automatic to
    Manual.

  • Since the last update my iCloud on my tablet is stuck in update will not let me sign out of it or chande anything  how can I stop the upgrade from running. I've tried everything nothing is working.

    My Apple iPad is stuck on the update in iCloud will not let me sign out of it or do anything in icloud. How can I get it to stop running. I have tried everything that I have looked up online and nothing works.  Every time I put in my apple ID it disables me. Ugg I am frustrated!

    Have just seen the answer to this in a another thread.
    Gilly

  • How can I stop the fan from running continuously on my iMac?  I have tried resetting the SMC and this did not work.

    I have a 27 in. iMac OS X, Version 10.7.5, Intel Core i5 and have a problem with the very loud and annoying fan running continuously.  The fan starts up immediately upon powering up and stays on all the time.  I have researched this on the internet and have tried resetting the SMC unsuccessfully.  Should I try fan control software?

    To reset the SMC means to reset the power management settings for your Mac. To do this, follow these simple steps.
    1) Shutdown your Mac by going to the Apple Logo in the upper left hand corner of the screen and selecting "Shut Down" from the drop down menu.
    2) Turn your machine back on while continuing to hold down the power button.
    3) After the initial boot chime, your power indicator light should flash three times.
    4) Your screen will remain black and you will hear the boot chime again. At this point, you may release the power button and allow your Mac to boot up normally. 
    All the best with getting your Mac Mini to run smoothly.

  • How to stop a process from running and display a message

    I have a button that inserts data into a table based on bind variable selected on the page. I would like to add code to that button that will check to see if certain data already exists in the table, for that bind variable, and if that data already exists, stop the process and display a message that says "you have already inserted that information - bla bla bla". If not, continue inserting. What would be the best way to do this?
    Currently, the button is a plsql that inserts the data.
    Any help or examples would be greatly appreciated!
    mholman
    Edited by: user10488561 on Jul 27, 2009 8:48 AM

    Use a validation process for that. If the validation fails (data exists) the processes will not be run. If it doesn't then the processing will continue.
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://www.opal-consulting.de/training
    http://apex.oracle.com/pls/otn/f?p=31517:1
    ------------------------------------------------------------------------------

Maybe you are looking for

  • Discoverer Desktop (4)- Receiving error Attempt to Open Workbook Failed

    Hi, The reason for this error is multiple people are opening same workbook. This has never been a problem before as the user would receive message: "Open Workbook as Read Only..." Now they only get the message: "Attempt to Open Workbook Failed." We h

  • Duplicate check while mapping

    Hello, I have a source message with 2 fields headerID and DetailID. The target is an IDoc structure with below snippet. Segment E1E337      HeaderID       Sub-Segment E1E440           DetailID HeaderID and DetailID in the IDoc segments are mapped to

  • I have a 13 inch MacBook Pro (2009) & the "White Screen of Death" is present.  Need help?

    I have a 13 inch MacBook Pro (2009).  Recently I bought an extended hard drive because I had used up the memory on my iDisk.  As I was running the Time Machine back up on my new extended drive, the battery on my Pro ran out causing it to shut down. 

  • Spry menu showing up incorrectly IE6

    Hi there, My spry menu horizontal bar is showing up incorrectly in IE6.... The buttons are meant to be maroon during hover, but they're all the default blue, sometimes when you hover over them they turn pink, sometimes blue, sometimes completely gray

  • Problem with ALSB Statistics Manager in cluster

    Hi, I setup a cluster with two nodes everything is OK except the below error message. It's from managed server Thanks a lot ###<ene 19, 2011 9:20:24 AM COT> <Error> <ALSB Statistics Manager> <LMASISWXP6456> <osb_server2> <[ACTIVE] ExecuteThread: '1'