Waiting for multiple threads to complete.......

Search the forum archives but have not found a definitive solution...
I have java app which spawns many threads (runnable objects) in the main() method. As one would expect, main exits before the threads finish but I don't want this to happen. I want to wait until all the threads have completed so I can use the results (stored in a vector) in the main thread....kindof like waitformultipleobjects in windows NT...
does any guru out there know how best to achieve this????
thanks

Have you tried using a ThreadGroup? I imagine something like the following. I think it is not so nice because of the empty while loop but you get the idea.
public class ThreadGroupTest {
     private static class Dummy extends Thread{
          private long sleepms;
          private String msg = null;
          public Dummy(ThreadGroup tg,long sleepms){
               super(tg,"test"+String.valueOf(sleepms));
               this.sleepms = sleepms;     
          public void run(){
               try {
                    Thread.sleep(sleepms);
               } catch (InterruptedException e) {
               this.msg="Slept "+String.valueOf(sleepms)+" millis.";
          public String getMsg() {
               return msg;
     public static void main(String[] args) {
          Dummy[] threads = new Dummy[10];
          ThreadGroup tg = new ThreadGroup("test");
          for(int i = 0;i<10;i++){
               threads[i] = new Dummy(tg,(i+1)*1000);
               threads.start();
          while(tg.activeCount()>0){
               System.out.println(tg.activeCount());
          for(int i=0;i<threads.length;i++){
               System.out.println(threads[i].getMsg());
Hope that helps.

Similar Messages

  • Waiting for multiple threads?

    I'm currently writing an app which, when a user opens a GUI screen, several threads are created which go away to load data. A "loading..." message should be displayed until all loading threads have completed.
    What's the best way to implement this?

    Ah yes. I was doing that, ish, but was doing:
    t1.start();
    t1.join();
    t2.start();
    t2.join();
    But of course it should have been:
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    Cool, thanks!

  • Waiting for many threads

    Hey guys,
    I know how to make one thread wait for another named thread to complete, but how do u make a thread wait for many threads to complete with the added problem of not knowing the names of the threads your waiting for? Looked and been trying for ages but can't get anything to work.
    Thanx
    Lisa

    No i saw it, pehaps i should rephrase with a question, how would you go about giving all these threads a reference? If it ain't obvious already am not great with java and if someone could tell me how to give the threads spawned references it would be great.
    As ive explained the code is really long so am not going to waist peoples time by posting it. Here is basically how i am spawning the threads "willy-nilly" style.
         while ((p < searchTerms.size())&&(p < 30)){
             term = (searchTerms.elementAt(p)).toString();
             NetChecker nc = new NetChecker(term,excludedAdds,refWeb);
             searchClasses.addElement(nc);     
             new Thread(nc).start();
             p++;
         } the classes all return web addresses in a vector, thats why i need all the threads to complete so i can collect all the results
    Thanx
    Lisa

  • Javascript: Wait for a redirect to complete - creating multiple PDF's

    Hi!
    Here is the code that I am using to try to generate multiple reports from javascript. how do I wait for the redirect to complete (ie. generate the PDF) before redirecting to generate the next PDF?
    In the code the "F106_" are application level items.
    I get have been able to get the very first or the very last PDF but none of the other PDF's.
    <script type="text/javascript">
    function f_DoReport() {
      for (i = 2; i <= 3; i++)
         for (j = 1; j <= 4; j++)
             var rgn = '0' + i;
             var dst = '0' + j;
             var vurl = 'f?p=&APP_ID.:30:&SESSION.:FLOW_XMLP_OUTPUT_R27022113101536736_en-us:&DEBUG.::';
             vurl += 'F106_RPT_REGION,F106_RPT_DISTRICT:' + rgn + ',' + dst;
             redirect(vurl);
             alert('rgn: ' + rgn + ' dst: ' + dst);
    </script>Please let me know if I am going down the wrong path here. :D
    As always thanks for your time and help!
    Dave Venus

    A few questions…
    Do you want a script that works with just the active document and you are going to run 300+ times? If so then this may do…
    #target illustrator
    function artboardsToPDFs() {
         if (app.documents.length = 0) {
              reurn;
         } else {
              var docRef = app.activeDocument;
              var docName = docRef.name;
              var baseName = docName.replace(/.ai$/,'');
              var dF = docRef.path.fsName;
              var aB = docRef.artboards;
              var pdfOpts = new PDFSaveOptions();
              pdfOpts.pDFPreset = '[Press Quality]';
              for (var i = 0; i < aB.length; i++) {
                   var numb = (i+1).toString();
                   pdfOpts.artboardRange = numb;
                   var pad = aB.length.toString().length;
                   numb = zeroPad(i+1, pad);
                   var pdfFile = File(dF + '/' + baseName + '_' + numb + '.pdf');
                   if (!pdfFile.exists) {
                        docRef.saveAs(pdfFile, pdfOpts);
                   } else {
                        var rPDF = confirm('File: "' + pdfFile.name + '" already exists…\rDo you wish to replace?',false);
                        if (rPDF) {
                             docRef.saveAs(pdfFile, pdfOpts);
                        } else {
                             continue;
    artboardsToPDFs();
    function zeroPad(n, p) {
      var t = n.toString();
         while (t.length < p) {t = '0' + t};
      return t;
    Do you want to pick a folder of all the illustrator files? If this is the case I would need more info and it would take longer…

  • Waiting for a thread to die.

    Hello, I hope you can help me...
    I am writting a jdk1.4.1 Swing application that displays a small animation. This animation is processed from within a separate thread. My program makes a call starting this 'animation thread'. For practical reasons my program needs to wait for this thread to die (and thus the full animation to be shown) before it can continue. I am waiting for the animation thread to die using Threads 'join' method. However the problem with this is that I am forcing the GUI thread to wait resulting in the animation being calculated but not displayed. And so... how can I fix this... all I want is to wait until the animation is shown.
    What I would like to do is:
    1. Start animation;
    2. wait intil animation has completed;
    3. continue with program.
    Any help or advice will be greatly appreciated.
    Thank you in advance.

    Maybe this design could work for you. You divide your program into three parts running in three separate threads.
    1. The main thread handling GUI stuff and coordination of the two other threads.
    2. A working thread doing most of what the main thread is now doing.
    3. The animation thread.
    With this division of labour the working thread is waiting for the animation thread to finish (the main GUI thread isn't). The main thread will be free at all times to react to the users input or updating the screen or whatever, while the other two threads are cooperating to produce the animation.

  • Does WPF waits for GPU present to complete?

    I'm testing how frequently WPF display can change when I have one window per monitor. My frame rate isn't amazing, and using xperf and GPUView it looks like WPF prepares both windows and then calls "Present packet" on both at the same time, and
    waits for both to complete before moving on to send the next frames to the video card. I think my frame rate could have been faster if WPF didn't wait for the present to complete on both displays. When I run two WPF processes, each with one window on
    one monitor, the present packets are independent, so parallel processing is more efficient and the frame rate is higher.
    Did anyone observe the same behavior? Is there a flag I can set to make the WPF windows of one process more independent? 

    Hello Shir Oren,
    I'm confused about those monitors, do you mean you have a computer with a few monitors?
    Then "When I run two WPF processes" can you briefly introduce it here? Different applications on different monitor? Do you actually mean thread but not process here?
    Actually WPF can take advantage of both Hardware and Software Rendering Pipeline, for details please refer to MSDN article:
    https://msdn.microsoft.com/en-us/library/bb613578(v=vs.110).aspx
    I'm not sure whether there is a flag you metioned but I haven't found it at this time. So I recommend you focus on the exist WPF render tiers from here
    https://msdn.microsoft.com/en-us/library/ms742196(v=vs.110).aspx to consider raise your performance.
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • SHUTDOWN: waiting for active calls to complete.

    Hello,
    environment is HPUX 11.23, Oracle Version is 9.2.0.5
    We had an ORA-600 error yesterday. We reported that error to the support and were suggested to install patch 9.2.0.8.
    However i have one question. As you can see from the output in the alert-logfile it took a very long time to shutdown the instance using the immediate option:
    Sun Nov 9 17:33:58 2008
    Shutting down instance: further logons disabled
    Shutting down instance (immediate)
    License high water mark = 454
    Sun Nov 9 17:39:07 2008
    Active call for process 3991 user 'oracle' program 'oracle@xyz (TNS V1-V3)'
    SHUTDOWN: waiting for active calls to complete.
    Sun Nov 9 17:50:36 2008
    ALTER DATABASE CLOSE NORMAL
    Is there anything one can do in such a situation to speed up the shutdown of the instance ?

    Rajabaskar Thangaraj,
    Oracle database has a job facility and a streams/advanced queuing facility.
    These facilities are possible by setting up a few ancillary processes.
    Those parameters govern the number of processes.
    Setting them to 0 will disable the facility completely.
    As you alter the parameter in memory, as you as you have bounced the database, it will be back to the value in the spfile and the facilities will work again.
    Disabling them is especially useful when you the facilities are frequently used, ie you have a job running every 30 seconds.
    In the past, on several databases, this was the only way to allow a shutdown immediate.
    Hope this helps,
    Sybrand Bakker
    Senior Oracle DBA

  • Application waits for the thread to finish

    Hi all,
    I have a class let say test that extends Thread.
    In my application i say:
    test Xtest = new test();
    Xtest.start();
    System.out.println("Thread finished");
    I need my application to wait for the thread to finish for it to continue, i.e. in my example print "Thread finished" .
    Can someone help me.
    Thanks in advance for your help.
    Best regards,
    Saadi MONLA

    This should work:
    test Xtest = new test();
    Xtest.start();
    Xtest.join();
    System.out.println("Thread finished");

  • I tried to import 2 photos from an email. The photos are now on iPhoto, however, when I try to close iPhoto or turn off my computer, I get a notice that says, "Photos are being imported to the photo library. Please wait for the import to complete."

    I tried to import 2 photos from an email to iphoto. The photos now appear in iphoto as the latest imports, However, when I try to close iphoto or log off of my computer, I get a message box that says, " Photos are being imported to the photo library. Please wait for the import to complete."
    I can't get out of iphoto or log off of my computer, or turn the computer off. How do I stop the import or log out of iphoto???

    Try Force-quit from the Apple-menu to close iPhoto.

  • Trying to download a program and get "Waiting for other installations to complete"

    Trying to download a program and get "Waiting for other installations to complete"
    there are no other instalations going on that I know of Please help

    That is for your and your Mac's protection; you need your administrator password to download/install things.

  • Microsoft Excel is waiting for another application to complete an Ole actio

    When I access Data Manager, I get the error message: "Microsoft Excel is waiting for another application to complete an Ole action."  When I click OK, I get another error: "Cannot download the dimension list from server.  Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached."  It never used to happen until recently.  I don't know what to tell the IT guys to do.  Thanks.

    This is a known error in V5. I have had this error at almost every V5 customer.
    The following solution (got it from support) solves it permanently.
    Changes have to be made to the outlooksoft.config file and the connectionstrings in tblappsetinfo. Be sure to restart the server(s) after applying these changes.
    1. In outlooksoft.config file of x:\OutlookSoft\Websrvr\bin folder on the web server change the following line:
    <add key="Database_AppServerDBConn" value="Server=<servername>;Database=AppServer;Trusted_Connection=True;"/>
    to
    <add key="Database_AppServerDBConn" value="Server=<servername>;Database=AppServer;Trusted_Connection=True;pooling=false"/>
    Please note that where I have <servername> you should put the name of your server ****
    Also, add the pooling=false; to every connection string in tblappsetinfo.
    I am sure this helps,
    Regards,
    Alwin Berkhout

  • Waiting for scheduling job to complete. Job ID...and it never completes

    I have created my first Publication. It's a pretty basic single source document, single Dynamic Recipients list publication.
    When I run it in Test mode (I haven't tried it in non-Test mode yet), the document(s) are never delivered.
    When I view the Log File, everything looks fine. The second and last entry in the log says
    "- The global delivery rule for this publication was met; publication processing will now begin."
    The Status Message I see in the Publication History is:
    "Waiting for scheduling job to complete. Job ID:3,879, name:Unviewed Invoices Report (Copy), kind:CrystalReport in Pending state (FBE 60509) [0 recipients processed.] "  and it never changes. I've tried this several times, creating new publications with the same source documents, and the same thing always happens.
    Any help would be appreciated.

    All of the servers were configured correctly.
    It turned out to be my source document, a report, had some field in it that BOE didn't like.
    I removed a bunch of fields and added them back, one by one, and couldn't make the error occur again.
    Go figure.

  • Installer keeps waiting for other installations to complete my downloads.  is this normal?

    I downloaded a microsoft remote desktop application and tried to download my office mac and the installer keeps saying waiting for other installations to complete.  So i thought i needed a restart and the installer won't shut down either.  is this normal?

    Immediate problem solved. After force quitting the Software Update app., iPhoto 9.2 appears to have been successfully installed and functional.  Unable to say if future S/W updates will encounter any problems. Thanks for all consideration. Item closed.
    Aubrey

  • Patched Deployments issue: "waiting for another installation to complete"

    I have some percent of computers which runs into above state in monthly patch deployments. I could minimal information from execmgmr, udpatesdeployment.log,
    CliSpy and Client Center etc tools but that doesn’t offer much help to nail down the issue completely. Have any of you dealt to resolve such issue successfully ? Is there any efficient way to handle this ?
    It seems I have
    DeploymentA, waiting for the completion of DeploymentB, which in turn waiting for the completion of
    DeploymentC. Is there any better approach I could take to nail down and resolve the issue. One of my finding is,  KB articles installs (SCCM R3, SCCM Asset Intelligence) causes these issue as they restart (upgrade sort of execution) the
    agent during the execution, I need to confirm these
    Vasu

    Hi Vasu,
    This issue can be caused by a deployment was previously deployed and was now deleted. This was because the clients finished installation
    and wanted to notify the Server that it is done, but since the deployment was deleted, it couldn’t Notify its progress to the site server and the CCM_DeploymentTaskEx1 got stuck.
    Please use the following scripts to delete the instance to test this issue.
    strService = "CcmExec"
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\CCM\SoftwareUpdates\DeploymentAgent")
    Set colWMISettings = objWMIService.ExecQuery("Select * from CCM_DeploymentTaskEx1")
    For Each objWMISetting in colWMISettings
    objWMISetting.AssignmentId = ""
    objWMISetting.JobId = "{00000000-0000-0000-0000-000000000000}"
    objWMISetting.Put_
    Next
    'Stop service
    Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'")
    objService.StopService()
    WScript.Sleep 10000 ' Pause to allow service to stop
    'Start service
    Set objService = objWMI.Get("Win32_Service.Name='" & strService & "'")
    objService.StartService()
    WScript.Sleep 10000 ' Pause to allow service to start
    Regards,
    Sabrina
    This posting is provided "AS IS" with no warranties or guarantees, and confers no rights. |Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
    This can be beneficial to other community members reading the thread.

  • Waiting for multiple Replies

    Hi all,
    in my Pub/Sub scenario, the subscribers should send a reply to the publisher through a temporary Topic. The publisher should receive all replies and treat all of them. It's no problem for me to gather the multiple replies (I have written my own Requestor that waits some seconds and during that time gathers the replies). However, this solution is improvable. There is a great chance that the waiting time is too short and the publisher misses some replies that could be very relevant. It would be great if the publisher could find out how many subscribers are currently subscribed and so find out for how many replies it should wait for. Has anyone an idea how to do that?
    TIA, Christian

    This is not defined as part of the specification. Some vendors offer RuntimeMBeans that allow you to get the information. However, without tighter coupling to JMS there would be races. Even registering for JMX notifications would not be enough to close the race. JMS would need to return the number of matched consumers.
    And in some cases the number would not be available. For instance, you send in a transaction. The message doesn't exist until you commit. So the vendor doesn't generally do any matching until commit time. By that time the send has long since completed. How would the count be returned to you.

Maybe you are looking for

  • Creative MediaSource Organiser cuts the sound off with latest driv

    I have an Audigy 2 ZS with the latest drivers and the latest Creative MediaSource Organiser. What happens for no reason is that playing some music, wav or mp3 the sound goes off. This does not happen with all songs. This affects everything, no sound

  • Mute button doesn't work to put phone in standby mode, help??

    I have a blackberry curve and the mute button will not work to put my phone in standby.  It does work to mute a phone call, however.  It has done this a couple of times, where it will work for awhile, and then stop working for awhile.  I'm not sure i

  • Error: You're browser does not support AJAX

    I am running my business software and I continue to get this error. I have safari, google chrome and firefox, but they all give me the same error. Any help? Is there some kind of plug-in or something that will allow me to use AJAX? Please help.

  • Adjusting reply to for Mail contact to an existing address.

    Hi all, would very much appreciate any advice on the following.  I have a mailbox forwarding mail to an external service (setup as a contact ) , the service then sends it back, I'd like the reply to address to be the original mailbox.  Example I emai

  • Application not found error message

    Everytime I try to download a purchased or free ebook (e.g. from Digital Editions site) I get the same error message: it lists the folder name of my temporary internet files\Content.IE5\Y9BKTFY\URLLink[22].acsm then it says Application not found. The