Wait in a thread

Hello All,
Can anybody tell me how can wait in a threadserver and when client notify wake up?
I noe I can use sleep but I don't know how to say that when you recive the message from clinet wake up?
Thanks for your help in advance

Just read(). It will block until the client sends something.

Similar Messages

  • 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.

  • 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");

  • 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

  • Wait screen and Thread

    Hi
    I am trying to build a general wait screen like this
    public class Wait extends javax.swing.JFrame {
        private Thread counterThread;
        private String titleWindow;
        public Wait(String title, Thread tr) {
            initComponents();
            this.setTitle(title);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
            counterThread = tr;
            try {
                URL url = new URL("file:///c:/Foronomos/resources/25-0.gif");
                Icon icon = new ImageIcon(url);
                jLabel1.setIcon(icon);
                jLabel1.setText("");
            } catch (Exception ex) {
          counterThread.start();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jButtonCancel = new javax.swing.JButton();
            jButtonStart = new javax.swing.JButton();
        }// </editor-fold>                       
    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {                                             
        counterThread.interrupt();
        // Variables declaration                     
        private javax.swing.JButton jButtonCancel;
        private javax.swing.JButton jButtonStart;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        // End of variables declaration                  
    }then am display the wait screen from a class creating a new thread
    ShowDocument showDocument = new ShowDocument();
    showDocument.showDocument(id, Main.searchDocuments.getQueryString());
    Thread counterThread = new Thread(showDocument, "showDocument");
    new Wait("Wait...",counterThread);
    ....my problem is that the wait screen delays to displayed on the screen an seems like to wait until the thread is finished
    Am i something missing here?

    TeoDim wrote:
    thanx for reply
    After the code new Wait("Wait...",counterThread);)
    i am not doing nothing.So you are doing something?
    Just if i press a button i want to display a screen with results from a long delay time query. So i want to display at that time a form with a messageFrom where are you execution the long running task? Where is it executing? Are you sure that you aren't using the AWT/Swing thread?

  • Object.wait(): IllegalMonitorStateException: current thread not owner

    How can I identify the owner? I searched the Thread*-Classes but didn't see any method which identifies the owner.

    Or, from the documentation for Object.wait():
         * The current thread must own this object's monitor.and
         * This method should only be called by a thread that is the owner
         * of this object's monitor. See the <code>notify</code> method for a
         * description of the ways in which a thread can become the owner of
         * a monitor. and
         * @exception  IllegalMonitorStateException  if the current thread is not
         *               the owner of the object's monitor.Seems like a lot of people are getting broken downloads nowadays that don't include the documentation :-(

  • Waiting the main thread till all child thread has completed

    I am in the process of developing a batch application in Java 5.0 which extensively uses the java.util.concurrency API. Here is a small description of what the batch process will do,
    1. Retrieve values from DB and populate a blocking queue in main thread.
    2. Instantiate a Threadpool by calling, Executors.newFixedThreadPool(2)
    3. Invoking the following block of code from the main thread,
    while(!iBlockingQueue.isEmpty()) {
        AbstractProcessor lProcessor = new  DefaultProcessor((BusinessObject)iBlockingQueue.remove());
        iThreadPool.execute(lProcessor);
    }DefaultProcessor is a class that extends Thread.
    4. Invoking the following block of code from the main thread,
    iThreadPool.shutdown();
    try {
         iThreadPool.awaitTermination(30, TimeUnit.SECONDS);
         } catch (InterruptedException interruptedException) {
              iLogger.debug("Error in await termination...", interruptedException);
    Since, this is the first time I am using the java.util.concurrency API, I want to know whether this is the right way to wait for all the child threads to complete before executing further statements in the main (parent) thread. Or do I necessariliy have to call join() to ensure that the main thread waits for all the child threads to finish which can only happen when the queue is empty.
    Please note here that as per the requirements of the application the blocking queue is filled only once at the very beginning.
    I will appreciate any inputs on this.
    Thanks.

    looks like you would be waiting on a queue twice, once in the loop and again, under the hood, in the threadpool's execute()
    the threadpool's internal queue is all that is needed
    if your iBlockingQueue is also the threadpool's internal queue, you might have a problem when you remove() the BusinessObject
    by making DefaultProcessor extend Thread you are, in effect, implementing your own threadpool without the pooling
    DefaultProcessor need only implement Runnable, it will be wrapped in a thread within the pool and start() called
    to implement a clean shutdown, I suggest writing DefaultProcessor.run() as an infinite loop around the blocking queue poll(timeout) and a stop flag that is checked before going back to poll
    class DefaultProcessor implements Runnable {
      private BlockingQueue myQ;
      private boolean myStopFlag;
      DefaultProcessor( BlockingQueue bq ) { myQ = bq; }
      public void run() {
        BusinessObject bo = null;
        while( !myStopFlag && (bo=myQ.poll( 10, SECONDS )) ) {
          // business code here
      public void stop() { myStopFlag = true; }
    } Now, after iThreadPool.shutdown(), either call stop() on all DefaultProcessors (or alternatively send "poison" messages to the queue), and give yourself enough time to allow processing to finish.

  • Waiting for a thread to finish

    I've been researching this issue for a couple of days, but I dont think I know enough about threading to ask the right question in a search engine. Sorry if this is a basic blunder....I dont write swing often and it shows.
    I have a swing app that includes a long task so I have implemented a progress bar. I need to wait until the progress bar task completes before continuing to the rest of the method. I've tried:
    1. Putting the progress bar within a while loop (while task not complete...) but the progress bar dialog does not render fully. I've even added repaint, but still the dialog looks blank.
    2. SwingUtilities.invokeLater, but it doesnt wait until the progress bar is finished
    3. SwingUtilities.invokeAndWait, though after all the reading I did about deadlock conditions I didnt like the idea. However I was desperate so I tried it and got an error:"Cannot call invokeAndWait from the event dispatcher thread".
    4. Putting the code that needs to occur after the progress bar in an "invokeLater" thread
    5. I've also used the ProgressBarDemo from the java.sun example with the swingworker hoping the worker thread would handle the issue.
    A much smaller version of the code is below:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class ProblemCode extends JFrame
         private JFrame jFrame = null;
         private JPanel jMain = null;
         private JButton startButton = null;
         public ProblemCode()
              initialize();
         public void initialize()
              //Setup the main application window size
              jFrame = new JFrame();
              jFrame.setContentPane(getJMainPanel());
              jFrame.pack();
              jFrame.addWindowListener(new java.awt.event.WindowAdapter()
                   public void windowClosing(java.awt.event.WindowEvent e)
                        dispose();
              SwingUtilities.invokeLater(new Runnable()
                public void run()
                    jFrame.setVisible(true);
         private JPanel getJMainPanel()
              if(jMain == null)
                   jMain = new JPanel();
                   jMain.add(getJStartButton());
              return jMain;
         private JButton getJStartButton()
              if (startButton == null)
                   startButton = new JButton();
                   startButton.setText("Start");
                   startButton.setVisible(true);
                   startButton.addActionListener(new ActionListener()
                       public void actionPerformed(ActionEvent e)
                           SwingUtilities.invokeLater(new Runnable()
                                 public void run()
                                          progBar();
                            System.out.println("Do this after the progress bar completes");
                            SwingUtilities.invokeLater(new Runnable()
                                 public void run()
                                      System.out.println("invokeLater doesnt work either....");
              return startButton;
         private void progBar()
            JFrame jProgFrame = new JFrame("JProgressBar Sample");
            jProgFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container content = jProgFrame.getContentPane();
            final JProgressBar progressBar = new JProgressBar();
            new Thread()
                private int counter = 0;
                private final int val = (int)(Math.random()*10)+1;
                public void run()
                    for(int i = 0;i <= 100;i++)
                        counter += val;
                        javax.swing.SwingUtilities.invokeLater( new Runnable()
                            public void run()
                                progressBar.setValue(counter);
                        try
                            Thread.sleep(500);
                        catch (InterruptedException e)
            }.start();
            progressBar.setStringPainted(true);
            Border border = BorderFactory.createTitledBorder("Reading...");
            progressBar.setBorder(border);
            content.add(progressBar, BorderLayout.NORTH);
            jProgFrame.setSize(300, 100);
            jProgFrame.setVisible(true);
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        new ProblemCode();
    }Thank you for taking the time to review this.

    Hi,
    I made some tiny changes in yoyr code, marked with
    // PBHere the changed code
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    public class ProblemCode extends JFrame {
        private JFrame jFrame = null;
        private JPanel jMain = null;
        private JButton startButton = null;
        public ProblemCode() {
         initialize();
        public void initialize() {
         // Setup the main application window size
         jFrame = new JFrame();
         jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // PB
         jFrame.setContentPane(getJMainPanel());
         jFrame.pack();
         jFrame.addWindowListener(new java.awt.event.WindowAdapter() {
             public void windowClosing(java.awt.event.WindowEvent e) {
              dispose();
         SwingUtilities.invokeLater(new Runnable() {
             public void run() {
              jFrame.setVisible(true);
        private JPanel getJMainPanel() {
         if (jMain == null) {
             jMain = new JPanel();
             jMain.add(getJStartButton());
         return jMain;
        private JButton getJStartButton() {
         if (startButton == null) {
             startButton = new JButton();
             startButton.setText("Start");
             startButton.setVisible(true);
             startButton.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                       progBar();
                  System.out
                       .println("Do this after the progress bar completes");
                  SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                       System.out
                            .println("invokeLater doesnt work either....");
         return startButton;
        private void progBar() {
         JFrame jProgFrame = new JFrame("JProgressBar Sample");
         jProgFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = jProgFrame.getContentPane();
         final int val = (int) (Math.random() * 10) + 1; // PB
         final JProgressBar progressBar = new JProgressBar(0, 100 * val); // PB
         progressBar.setStringPainted(true);
         Border border = BorderFactory.createTitledBorder("Reading...");
         progressBar.setBorder(border);
         content.add(progressBar, BorderLayout.NORTH);
         jProgFrame.setSize(300, 100);
         jProgFrame.setVisible(true);
         // PB
         final Thread longTask = new Thread() {
             private int counter = 0;
             public void run() {
              for (int i = 0; i <= 100; i++) {
                  counter += val;
                  javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                       progressBar.setValue(counter);
                  try {
                   Thread.sleep(100); // PB
                  } catch (InterruptedException e) {
         longTask.start();
         // PB
         Thread followUpTask = new Thread(new Runnable() {
             @Override
             public void run() {
              try {
                  System.out.println("Follow up task is waiting");
                  longTask.join();
                  System.out.println("Follow up task  continues");
              } catch (InterruptedException e) {
                  e.printStackTrace();
         followUpTask.start();
        public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
             public void run() {
              new ProblemCode();
    }Piet

  • Standby media recovery waiting for inactive thread

    Hi,
    Please let me know any idea on this scenario. Thanks.
    Environment:
    Oracle 11.2.0.2
    primary: 3 node RAC
    standby: 3 node RAC
    Problem:
    there is thread 5 (not registered instance or did not show in srvctl) that generates archivelog. but the lag apply stopped because of this when the instance (of thread 5) is shutdown.
    question: somehow an instance is registered in the cluster but in srvctl only 3 instance is running. it should have 4 instance but 1 is not running. How can I remove the thread 5 so when someone startup then shutdown instance#4 it will not create archivelog that will stopped the apply of archivelog in standby.
    note: this is perf environment server so someone and "other" DBA is accessing this environment which I am not aware what are they doing with the cluster.
    looking in alert log file: - it is waiting for thread 5 sequence 510. But the instance is down so log is not shipped to standby database and this resulted to lag in other threads.
    Sat Aug 03 18:54:47 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_1_seq_13718.1544.822333555
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_2_seq_17665.22678.822315375
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15465.14138.822313997
    Media Recovery Waiting for thread 5 sequence 510
       THREAD# LAST_SEQ_RECEIVED LAST_SEQ_APPLIED
             1             13745            13717
             2             17728            17664
             3             15527            15464
             5               509              509
    what I did is:
    1. primary (asm copy to file system)
    2. scp primary to standby
    3. standby (file system copy to asm)
    4. rman target / -> catalog archivelog <thread 5 sequence 510)
    5. then looking into alert log file; it performed media recovery
    Sat Aug 03 23:03:13 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_1_seq_13718.1544.822333555
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_2_seq_17665.22678.822315375
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15465.14138.822313997
    Media Recovery Waiting for thread 5 sequence 510
    Sat Aug 03 23:15:21 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_5_seq_510
    Sat Aug 03 23:15:32 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15466.10925.822316315
    Sat Aug 03 23:17:18 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_2_seq_17666.853.822333143
    Sat Aug 03 23:18:39 2013
    Media Recovery Log +FLASH/dgjmspl/archivelog/2013_08_01/thread_3_seq_15467.834.822333553
    Sat Aug 03 23:20:54 2013

    in Standby, thread 4 and 5 are both UNUSED, and size is incorrect (not equal to other redo log). I want to recreate it but cannot drop redo log. I follow Doc ID 740675.1.
    any idea what are the missing steps? thanks.
    ORA-01624: needed for crash recovery of instance UNNAMED_INSTANCE_5 (thread 5)
    select group#,thread#,archived,status,bytes from v$log;
    primary DB:
        GROUP#    THREAD# ARC STATUS                BYTES
             1          1 YES INACTIVE         1073741824
             2          1 YES INACTIVE         1073741824
             3          2 NO  CURRENT          1073741824
             4          2 YES INACTIVE         1073741824
             5          3 YES INACTIVE         1073741824
             6          3 YES INACTIVE         1073741824
             7          2 YES INACTIVE         1073741824
             8          1 NO  CURRENT          1073741824
             9          3 NO  CURRENT          1073741824
            10          4 YES INACTIVE         1073741824
            11          4 NO  CURRENT          1073741824
        GROUP#    THREAD# ARC STATUS                BYTES
            12          4 YES INACTIVE         1073741824
            13          5 YES INACTIVE         1073741824
            14          5 YES INACTIVE         1073741824
            15          5 NO  CURRENT          1073741824
    standby DB:
        GROUP#    THREAD# ARC STATUS                BYTES
             1          1 YES INACTIVE         1073741824
             2          1 YES INACTIVE         1073741824
             3          2 NO  CURRENT          1073741824
             4          2 YES INACTIVE         1073741824
             5          3 YES INACTIVE         1073741824
             6          3 YES INACTIVE         1073741824
             7          2 YES INACTIVE         1073741824
             8          1 NO  CURRENT          1073741824
             9          3 NO  CURRENT          1073741824
            10          4 YES INACTIVE         1073741824
            11          4 NO  CURRENT          1073741824
        GROUP#    THREAD# ARC STATUS                BYTES
            12          4 YES INACTIVE         1073741824
            13          5 YES INACTIVE         1073741824
            14          5 YES INACTIVE         1073741824
            15          5 NO  CURRENT          1073741824

  • Wait while event thread has been removed all events

    hi,
    how can i wait while the event thread has been work out all its events in the queue? is there something like eventQueue.isEmpty();???

    Have a look at invokeLater()

  • 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.

  • Waiting on unknown threads to finish

    I have made the ExecutionService class, and now i have a small problem. The point of the class was to split the job normally done by one thread into as many as possible. Now, i need the thread that called executeInstantly/waitToExecute to wait until the requested task(s) are done, and there are no more tasks to process. What would be the best way to implement that? Note, only one thread will be adding to the Queue of tasks, and its the same one that needs to wait on them to finish.
    package jad.util;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    public class ExecutionService {
        public ExecutionService() {
            runnableTasks = new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE);
            initializeExecutors(Runtime.getRuntime().availableProcessors());
        public ExecutionService(BlockingQueue<Runnable> blockingQueue) {
            runnableTasks = blockingQueue;
            initializeExecutors(Runtime.getRuntime().availableProcessors());
        public ExecutionService(final int NUM_THREADS, final int MAX_JOBS) {
            runnableTasks = new LinkedBlockingQueue<Runnable>(MAX_JOBS);
            initializeExecutors(NUM_THREADS);
        private final void initializeExecutors(final int NUM_THREADS) {
            for (int i = 0; i < NUM_THREADS; i++) {
                createNewExecutor();
                ++numThreadsRunning;
        private final Runnable getPermTask() {
            return new Runnable() {
                @Override
                public void run() {
                    Exception ex = null;
                    try {
                        while (continueRunning) {
                            getNewTask().run();
                    } catch (InterruptedException e) {
                        (ex = e).printStackTrace();
                    } catch (Exception e) {
                        (ex = e).printStackTrace();
                    } finally {
                        if (ex != null) {
                            createNewExecutor();
        private Executor createNewExecutor() {
            return new Executor(getPermTask());
        private Runnable getNewTask() throws InterruptedException {
            return runnableTasks.take();
        public boolean executeImmediately(Runnable task) throws Exception {
            if (!continueRunning) {
                throw new Exception("ExecutorService instance is shut down");
            return runnableTasks.offer(task);
        public void waitToExecute(Runnable task) throws InterruptedException, Exception {
            if (!continueRunning) {
                throw new Exception("ExecutorService instance is shut down");
            runnableTasks.put(task);
        public void shutDown() {
            continueRunning = false;
            Runnable emptyTask = new Runnable() {
                @Override
                public void run() {
                    return;
            for (int i = 0; i < numThreadsRunning; i++) {
                try {
                    waitToExecute(emptyTask);
                } catch (InterruptedException e) {
                    System.out.println("Could not shut down!");
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
        private int numThreadsRunning = 0;
        private volatile boolean continueRunning = true;
        private BlockingQueue<Runnable> runnableTasks;
    class Executor {
        public Executor(Runnable task) {
            Thread t = new Thread(task);
            t.setDaemon(true);
            t.setName("Executor service thread");
            t.start();
    }Edited by: Jadz_Core on Aug 6, 2009 9:36 PM

    You would use a java.util.CountDownLatch if you only wanted to wait for the tasks currently executing and waiting in the queue (for example, there would be no tasks added AFTER the waiting began). I think this is suitable for your situation since you said there would be just one thread adding to the queue.
    Pseudocode:
    class ExecutorService {
        private volatile CountDownLatch counter = new CountDownLatch(Integer.MAX_VALUE);  //start countdown latch at really high values
        private AtomicInteger activeThreadCount = new AtomicInteger(0); //keep track of threads actually working
        private BlockingQueue queue; //keep waiting tasks
        class PermTask implements Runnable
            public void run()
                while (!shutdown)
                    Runnable task = queue.take();
                    activeThreadCount.incrementAndGet();
                    try
                        taskToRun.run();
                    finally
                        activeThreadCount.decrementAndGet();
                        counter.countDown();
        public void waitForTasksToComplete()
            int totalTasks = queue.size() + activeThreadCount.get();
            counter = new CountDownLatch(totalTasks);
            counter.await();
        }This would take a bit of cleaning up, for instance you have to protect the activeThreadCount and the counter so that the values don't change in the middle of some work (a ReadWriteReentrantLock might work nicely here - the PermTask would acquire Read Locks so they don't block each other. The wait... method acquires a Write lock to it waits for Reads to finish, and blocks more Reads until it is done). But it should get you started.
    Edited by: stevejluke on Aug 7, 2009 7:01 AM

  • How to use Wait Screen and Thread?

    Greetings,
    I was wondering If I could ask a question...
    Here it goes:
    How can I use a Wait Screen in a MIDlet so that I can do the Following:
    1.- Create and Open an Http Connection[b[i]](using an Object which extends Thread) in a Form by pressing an OKCommand.
    2 .- Show the Wait Screen Until the Thread Object finishes execution(finishes whatever is inside run() method)
    3.- Finally show the Result(s) of the Connection(bytes obtained from URL) in another Form.
    First of all, Is what I ask even possible? and more importantly...
    Can a Wait Screen actually Detect when a Thread finished execution? so that only when the thread finishes the program proceeds to the next statement?
    Thank you very much in advance!
    Sincerely, your friend,
    Jose

    Thank you very much Sir, I suppose that narrows it down a bit,
    Because I definitely need my applications as standard as possible.
    But good to know there's a way to do it.
    Well, Thank you very much as usual!
    Sincerely,
    Keep up with the fantastic job you do every day!
    God Bless.
    J

  • Wait synchro between threads

    At the moment, the support of a touch restarts all the threads

    A wait step only waits for a specific amount of time or for a thread or execution to complete.
    If you want to "wait" for a signal and only allow one thread to respond, you should use notification steps and use the pulse operation by specifying to only notify first thread that waits.
    Scott Richardson
    Scott Richardson
    National Instruments

  • Wait for all threads in a array to die

    I everyone. I'm from Portugal and I have some experience in JAVA programming (approximately five years) but this is the first the first time that i'm trying to use threads. I'm trying to learn writing some simpler code that does almost exactly at the basic level the same stuff that a complex application that I need to write for my work.
    What I'm trying to do is execute a counter that counts all operations in threads belonging to the same array (an array of n threads).
    A static variable in the Thread class (implementing Runnable) counts all operations performed by all threads and sums them all and shoud display the total of operations after all threads terminate, but this exactly what I don't know how to do:
    This is my example code:
    public class TT1 implements Runnable {
         int id;
         double last_number;
         static int threads_counter = 0;
         static int total_threads = 4;
         static long total_numbers;
         int total_randoms = 1000;
         public void run() {
              for (int i=0;i<total_randoms;i++)
                   total_numbers++;
                   // does some stuff, in this case, generate a random number!
                   last_number = Math.random();
              System.out.printf("Thread %d:%f(%d)\n",id,last_number,total_numbers);
         public TT1() {
              id = threads_counter++;
              new Thread(this).start();
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Thread [] threads = new Thread[total_threads];
              for (int i=0;i<threads.length;i++)
                   threads[i] = new Thread(new TT1());
              /* commented code using join(), is not working or I don't know
              how to use it! */
              for (int i=0;i<threads.length;i++)
                   try {
                        threads.join();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              try {
                   threads[total_threads-1].join();
              } catch (InterruptedException e) {
                   e.printStackTrace();
              // this line should be executed ONLY after ALL threads have died!
              System.out.println("******GENERATED NUMBERS TOTAL:" + total_numbers);
    Somebody can give me a hint how to solve this ?

    Thanks for your replies.
    Actually, i've corrected the code, now i'm starting the threads outside the constructor. Originally I thought this could be a simpler way to create the threads: launching them at same time I'm creating them! Is this wrong ? :) Well, watching the results.
    I changed my code:
    public class TT1 implements Runnable {
         int id;
         double last_number;
         static int threads_counter = 0;
         static int total_threads = 4;
         static long total_numbers;
         int total_randoms = 1000;
         public void run() {
              for (int i=0;i<total_randoms;i++)
                   total_numbers++;
                   // does some stuff, in this case, generate a random number!
                   last_number = Math.random();
              System.out.printf("Thread %d:%f(%d)\n",id,last_number,total_numbers);
         public TT1() {
              id = threads_counter++;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Thread [] threads = new Thread[total_threads];
              /* create individual threads */
              for (int i=0;i<threads.length;i++)
                   threads[i] = new Thread(new TT1());
              /* launch the threads (NEW CODE) */
              for (int i=0;i<threads.length;i++)
                   threads.start();
              /* commented code using join(), is not working or I don't know
              how to use it! */
              for (int i=0;i<threads.length;i++)
                   try {
                        threads[i].join();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              // this line should be executed ONLY after ALL threads have died!
              System.out.println("******GENERATED NUMBERS TOTAL:" + total_numbers);
    And I obtain the output:
    $ java TT1
    Thread 0:0,191546(1000)
    Thread 1:0,937476(2000)
    Thread 2:0,825079(3000)
    Thread 3:0,451367(4000)
    ******GENERATED NUMBERS TOTAL:4000Exactly as I want it!
    All is good when it works good ;)
    Best regards

Maybe you are looking for

  • 5700 New FirmWare???

    Hey Guys I bought New Nokia 5700 Xpress Music Please Tell Me That When Nokia Will Release It's Newer Firmware I have v03.27 And Can ANy One Tell Me The Best Configuration for Loud SOund ALthogh It's SOund Is Rocking But please Tell ME The Best Config

  • Document Split Up - New GL

    Dear Sir, I want to split the document of following example Document splitting examples u2013 Vendor Invoice Vendor Invoice for two purchases Tax amount I hvae configured the following configuration Classify the G/L accounts Classify document types D

  • Failover cluster installation

    Hello, I would like to install SAP ECC6 EhP4 from System Copy (backup/restore) in Windows failover cluster environnement with two nodes. So, I have installed MSSQL Server 2008R2 SP2 in cluster mode (using virtual host : FRSERVERSQL). Now, I have to i

  • Webdavfs broken in Mavericks

    I just noticed that i couldn't mount my webdav from finder anymore after the Mavericks update. I checked the logs and found: 2013-10-24 17:00:25,547 webdav_cert_ui[2291]: Unable to load nib file: MainMenu, exiting Which would mean that the nib file c

  • HT200094 Import from iPhoto

    I can't find my iPhoto pictures/movies to import into final cut pro x. What happened? I have the newest update. I did go to the image button and picked that way and just dragged them into my new event. what a pain in the pattottie. What happed to the