Wait() and notify() porblems.

public class test {
     public static void main(String[] args) {
          new consumer();
          new producer();
class producer extends Thread
     public static int productcnt=0;
     public consumer aconsumer=new consumer();
     producer()
          super("producer : "+ productcnt++);
          start();     
     public void run()
          try
                    sleep(1000);
                    synchronized (aconsumer)
                         System.out.println(this.getName()+" has prepared.");
                         aconsumer.notify();
          catch(InterruptedException e)
               throw new RuntimeException(e);
class consumer extends Thread
     public static int consumercnt=0;
     consumer()
          super("consumer : "+ consumercnt++);
          start();
     public void run()
          try
                    synchronized(this)
                         System.out.println(getName()+ " is waiting.");
                         wait();
                         System.out.println(getName()+ "  get product.");
          catch(InterruptedException e)
               throw new RuntimeException(e);
}We can see the code about producers and consumers above,and the result is:
consumer : 0 is waiting.
consumer : 1 is waiting.
producer : 0 has prepared.
consumer : 1 get product.
---------------------------------------at the end of program ,consumer 0 is waiting however.
consumer 0,started in the main procedure,I can't stop it, who can tell me how tostop it with a notify.
is it real that consumer just can be notified in a procedure which claimed it?

The answer is:
public class Test {
     public static void main(String[] args)
          consumer cs = new consumer(); // ---------
          new producer(cs);
class producer extends Thread
        public static int productcnt=0;
        consumer cs;  // ---------
        public consumer aconsumer=new consumer();
        producer(consumer cs)
           super("producer : "+ productcnt++);
           this.cs = cs;  // ---------
           start();       
       public void run()
             try
                    sleep(1000);
                     System.out.println(this.getName()+" has prepared.");
                    synchronized (cs)  // ---------
                         cs.notify();          // ---------
                   synchronized (aconsumer)
                          aconsumer.notify();
              catch(InterruptedException e)
                       throw new RuntimeException(e);
class consumer extends Thread
        public static int consumercnt=0;
        consumer()
            super("consumer : "+ consumercnt++);
            start();
       public void run()
               try
                       synchronized(this)
                                System.out.println(getName()+ " is waiting.");
                                 wait();
                                 System.out.println(getName()+ "  get product.");
               catch(InterruptedException e)
                       throw new RuntimeException(e);
}Well, I simply tried to not to change your code essentially. If you gonna do something like this
but more complicated try to find other solution.

Similar Messages

  • A bug in wait and notify? -- help

    Now I am engaged in a simulation project. The threads are all controlled by the controller program, that is, they are often blocked and unblocked by using wait and notify methods. However, when I was debugging my program, there were always some errors occurring and halting the simulation. And I found that the cause was that the threads sometimes might halt after having executed the wait or notify methods!!
    Example,
    in thread 1, it would be blocked by a wait method like:
    synchronized(lock){
    lock.wait();
    System.out.println("Thread 1 go on.");
    In thread 2, it would unblock thread 1 with the notify method:
    synchrnoized(lock){
    System.out.println("Thread 2 would notify the threads blocked on lock.");
    lock.notifyAll();
    System.out.println("Thread 2 go on.");
    The simulation program controls the time to execute the thread 2. However, in debugging the program I often encountered the problem that thread 2 did notify thread 1 and thread would go on executing, but thread 2 would not go further. That is, the output is like:
    Thread 2 would notify the threads blocked on lock.
    Thread 1 go on.
    But the String, "Thread 2 go on." would not be printed out.
    It was so strange, and I repeated for tens of times, it always occurred here and there.
    Is it a bug of java?

    There seems to be nothing wrong with this to me:
    You should use better debugging messages. I couldn't read it the way you had it.
    public class BugThread extends Thread
        Object lock;
        Notifier notifier;
        public static void main(String[] arg)
            for(int i = 0; i < 5; i ++)
                Object lock = "lock " + i;
                Notifier noti = new Notifier(lock);
                BugThread bug = new BugThread(lock, noti);
                bug.start();
                noti.start();
        public BugThread(Object lock, Notifier notifier)
            this.lock = lock;
            this.notifier = notifier;
        public void run()
            int i = 0;
            while( i++ < 100)
                synchronized(lock)
                    System.out.println("Bug thread: "
                        + lock + " would block at Object: "
                        + lock);
                    try
                        lock.wait();
                    catch(InterruptedException ex)
                        ex.printStackTrace();
                    System.out.println("Bug thread: "
                        + lock + " unblocked at Object: "
                        + lock);
            notifier.stop();
    class Notifier extends Thread
        Object lock;
        public Notifier(Object lock)
            this.lock = lock;
        public void run()
            int i = 0;
            while(true)
                synchronized(lock)
                    System.out.println("Notifier: " + lock
                        + " would notify Bugthread blocking at object: "
                        + lock.toString() + ". time no." + i);
                    lock.notifyAll();
                    System.out.println("Notifier: " + lock
                        + " notified bugthread. time no." + i);
                System.out.println("Notifier: " + lock
                    + " go on working. time no." + i);
                i ++;
    }

  • Wait and notify in servlets?

    i am having a servlet , which is implementing wait and notify of java.lang.Object.
    when serving it for single request , its waiting and working fine...
    but for multiple requests its not serving properly. works one by one means the second request is waiting for finishing the first request just like SingleThreadModel (after finishing the first request only second request entering inside servlet)
    please help me to solve this?
    or is there any other way to call wait method without synchronized block??

    Shynihan wrote:
    or is there any other way to call wait method without synchronized block??No, and that's partly because if wait or notify is the only thing in the synchronized block then you probably aren't using them right. The problem is blocking the server thread. Servlet engines use a thread pool to execute transactions, when a new transaction comes in a thread is taken from the pool to run it, and there's usually a limited number of threads in the pool. If there's no threads left then the transaction will wait for another to finish.
    If your servlets freeze up, then that's a thread gone from the pool.
    And remeber the unlocking transaction may never arive. The client could go down at any time, leaving the server thread permanently hung.
    You need to move this waiting to the client side. If the transaction cannot proceed then return a "come back later" response immediately. The client can then retry after a decent interval.

  • Wait and notify in Object

    Hi,
    Who can give me a short java code segment to show the method wait and notify of the class Object.
    I've already tryed as forlow:
    try {
    A a = new A();
    a.wait() ;
    catch (InterruptedException ex) {
    ex.printStackTrace() ;
    But a thread is always be thrown:
    java.lang.IllegalMonitorStateException: current thread not owner
         at java.lang.Object.wait(Native Method)
         at java.lang.Object.wait(Object.java:420)
         at A.main(A.java:34)
    Who can tell which thread should be the owner thread? I did realize noly one thread there.
    Thanks a million.

    The classic example is two threads, on adding items to a queue and one taking them off and processing them:
    // consumer
    Object item = null;
    do {
       synchronized(queue) {
          if(queue.isEmpty())
              queue.wait();
        item = queue.remove(0);
      // process item
      } while(!Thread.currentThread.isInterrupted());
    // producer
    synchronized(queue) {
        if(queue.isEmpty())
          queue.notify();
       queue.add(item);
       }The use of synchronized blocks or methods is essential. They guard against conflicts and race conditions between different sections that change the same data.

  • Why  wait  and notify kept in object class only

    why wait and notify kept in object class only. is it maintain locks while doing wait and notify . please explain internals,

    What do you mean in Object class "only"? If they're in Object, then they're in ALL classes.
    They're in Object because any Object can serve as a lock.
    For details of how to use them, see a Java threading tutorial such as http://java.sun.com/docs/books/tutorial/essential/threads/

  • Wait() and notify() or Semaphores with single permits?

    Hi,
    What's the difference between using wait(), notify() and single permitted Semaphores? Does using the latter affect the performance in massively multi-threaded environments?

    I wrote a very simple program to simulate a Queue like structure, and a Producer with a Consumer which both are running in separate threads. I changed the Queue class to hold only one value (It's not a queue any more, but the name didn't change). Then I used a boolean value, wait() and notify() methods of the Object class to ensure that every put() by the producer is followed by a get() by the consumer. Here's the Queue class code:
    class Queue {
         private int num;
         private boolean valueSet = false;
         synchronized void put(int n) {
              while(valueSet) {
                   try {
                        wait();
                   } catch(InterruptedException err) {
                        System.out.println("put() interrupted.");
              num = n;
              valueSet = true;
              notify();
              System.out.println("Put: "+n);
         synchronized int get() {
              while(!valueSet) {
                   try {
                        wait();
                   } catch(InterruptedException err) {
                        System.out.println("get() interrupted.");
              valueSet = false;
              notify();
              System.out.println("Got: "+num);
              return num;
    }Producer and Consumer classes simply repeat calling put() and get() methods respectively for a number of times. I also implemented all this by using Semaphores with single permits:
    import java.util.concurrent.*;
    class Queue {
         private int num;
         private final static Semaphore semCon = new Semaphore(0);
         private final static Semaphore semPro = new Semaphore(1);
         void put(int n) {
              try {
                   semPro.acquire();
              } catch(InterruptedException err) {
                   System.out.println("put() interrupted.");
              num = n;
              semCon.release();
              System.out.println("Put: "+n);
         int get() {
              try {
                   semCon.acquire();
              } catch(InterruptedException err) {
                   System.out.println("get() interrupted.");
              semPro.release();
              System.out.println("Got: "+num);
              return num;
    }Which one is better? Better in every aspect, such as performance, being maintainable, etc. I don't know whether it's a good idea to use Semaphores in these cases.
    Thanks for your reply.

  • Wait and notify

    I have a main that calls a drawing window. The user draws in the window and clicks a button when finished drawing. Then main then gets this image. I don't know how to call the getImage in the main ONLY after the user has clicked the button in the draw window, however. I've heard about wait and notify commands, but I don't know how to use them. Can anyone help me? Thanks.

    Oh my... I'm not a java superstar. I'll post my code and maybe someone can help me. I tried running wait, but it says not thread owner or something weird.
    Main:
    public static void main (String [] args) throws IOException, InterruptedException, AWTException
            Image image = null;
            PaintArea pa = new PaintArea ();
            pa.loadArea (pa);
            //After screen capture
            image = pa.getImage ();}PaintArea:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    class PaintArea extends Frame
        static int x, y;
        static Image image;
        Canvas canvas = null;
        PaintArea ()
            setSize (110, 160);
            setVisible (true);
            addWindowListener (new WindowAdapter ()
                public void windowClosing (WindowEvent e)
                    hide ();
        public void loadArea (PaintArea pa) throws InterruptedException
            Button button = new Button ("Save");
            Canvas drawArea = new Canvas ();
            drawArea.setSize (100, 100);
            canvas = drawArea;
            pa.setLayout (new BorderLayout ());
            pa.add (drawArea, BorderLayout.CENTER);
            pa.add (button, BorderLayout.SOUTH);
            pa.show ();
            Graphics g = drawArea.getGraphics ();
            final Graphics g2 = g;
            final PaintArea pa2 = pa;
            button.addActionListener (new ActionListener ()
                public void actionPerformed (ActionEvent ae)
                    try
                                          image = saveScreen (pa2);
                    catch (AWTException e)
                        System.err.println (e);
                        System.exit (1);
                    catch (InterruptedException ie)
                        System.err.println (ie);
                        System.exit (1);
            drawArea.addMouseListener (new MouseAdapter ()
                public void mousePressed (MouseEvent me)
                    x = me.getX ();
                    y = me.getY ();
                    g2.fillOval (x - 5, y - 5, 10, 10);
            drawArea.addMouseMotionListener (new MouseMotionAdapter ()
                public void mouseDragged (MouseEvent me)
                    x = me.getX ();
                    y = me.getY ();
                    g2.fillOval (x - 5, y - 5, 10, 10);
        public Image saveScreen (PaintArea pa) throws AWTException
            Image image = null;
            try
                image = createImage (new Robot ().createScreenCapture (pa.getDrawArea ().getBounds ()).getSource ());
            catch (NullPointerException npe)
                System.err.println (npe);
                System.exit (1);
            return image;
        public Picture getImage ()
            return image;
        public Canvas getDrawArea ()
            return canvas;
    }Could someone please run that and try to make the pa.getImage() in the main happen only after the button in Paint Area is pressed? Thanks!

  • IllegalMonitorStateException? wait() and notify()

    Can someone tell me what's the deal with wait() and notify() methods? Like how to use them properly? Right now I have two threads, one being the main program and the other should run occationally when I need it... I try to get the second to wait() and second.notify() when I want to to run but IllegalMonitorStateException... so if you know a tutorial or you can explain it me it'll be great!
    Thanks!

    This is a bit hard to answer without a code example. Have you gone through the tutorial available on this topic?
    http://java.sun.com/docs/books/tutorial/essential/threads/index.html
    If you have already looked at these, post your sample code (inside code tags, please - use the code button above) so others can read it and run it.

  • Stuck with wait() and notify()

    Hi,
    I have a problem understanding synchronous access.
    I have an object that should provide a list of data. The list is used later in my code, but it would increase performance to load it in a separate thread at the beginning. However it is possible that the list is not ready when the first other object tries to access the list.
    I thought that this code should solve the problem
    public class SingleObject implements Runnable {
         ArrayList list;
         public SingleObject(){
              list = new ArrayList();
         public synchronized void run() {
              try {
                   makeALongProc(100);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              notify();
         private synchronized void makeALongProc(int size) throws InterruptedException{
                   System.out.println("...doing something ...");
                   Thread.sleep(5000);
                   for (int i = 0 ; i < size ; i++ ){
                        list.add(""+i);
                   System.out.println("finished!");
                   notifyAll();
         public synchronized String getValueAt(int pos) throws InterruptedException{
              wait();
              return list.get(pos).toString();
         public synchronized List getList() throws InterruptedException{
              wait();
              return list;
    } The object is invoked by the following code.
    public class ThreadProject {
          * @param args
         public static void main(String[] args) {
              System.out.println("...starting thread...");
              SingleObject so = new SingleObject();
              Thread th = new Thread(so);
              th.start();
              try {
                   System.out.println("waiting ...");
                   List list = so.getList();
                   System.out.println("got list"+list.size());
                   String sso = so.getValueAt(5);
                   System.out.println(sso);
              } catch (InterruptedException e) {
                   e.printStackTrace();
    }Unfortunateley this is not doing what I have expected. Instead of calling the methodsso.getList() and so.getValueAt() it enters so.getList() and waits and waits....
    Can anybody give my a clue or an explanation what I am doing wrong?
    Regards
    Sas
    Message was edited by:
    Poncho1975

    I have tried a little bit further.
    I changed the following part:
    public class SingleObject {
         ArrayList list;
         public SingleObject(){
              list = new ArrayList();
         public synchronized void makeALongProc(int size) throws InterruptedException{
              System.out.println("...doing something ...");
              Thread.sleep(5000);
              for (int i = 0 ; i < size ; i++ ){
                   list.add(""+i);
              System.out.println("finished!");
              notify();
         public synchronized String getValueAt(int pos) throws InterruptedException{
                    if (list==null || list.size()<=pos){
                          wait();
              return list.get(pos).toString();
         public synchronized List getList() throws InterruptedException{
              if (list==null){
                          wait();
              return list;
    }and ...
    public class ThreadProject {
          * @param args
         public static void main(String[] args) {
              System.out.println("...starting thread...");
              final SingleObject so = new SingleObject();
              Thread th = new Thread(new Runnable(){
                   public synchronized void run() {
                        try {
                             so.makeALongProc(100);
                        } catch (InterruptedException e) {
                             e.printStackTrace();
              th.start();
              try {
                   System.out.println("waiting ...");
                   List list = so.getList();
                   System.out.println("got list"+list.size());
                   String sso = so.getValueAt(5);
                   System.out.println(sso);
              } catch (InterruptedException e) {
                   e.printStackTrace();
    }Now I am satisfied. Every call on a method from this object would lead to the situation, that either makeALongProc is called first or all other methods must wait until makeALongProc has been called once to fill the array.
    However I suppose that accessing elements of a list with a synchronized object is not a good decision. I would rather take only the whole List and do all other access outside of the object.
    Regards
    Poncho

  • How to fix wait and notify

    The program tries to find the first socket connection. Theirs a wait and the notify call in the inner class seams to have to effect. Attach is the code to try out
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import java.nio.channels.*;
    * SocketSearch class to scan for an open socket from an array of sockets passed. <br>
    * Inner class DetectSocketConnection tries to open the socket and assign hostname
    * a value if successful. <br>
    * The SocketSearch thread class is waiting to find the hostname or active DetectSocketConnection
    * threads to be zero - i.e No hosts found
    public class SocketSearch extends Thread {
       private Object syncObject = new Object();
       private String hostname = null;
       private ThreadGroup threadGroup = new ThreadGroup("SOCKETS_CONNECT");
       private ArrayList sockets = null;
        * Inner class DetectSocketConnection to find an open socket. <br>
        * It will assign the hostname a value if successful
       private class DetectSocketConnection extends Thread {
          private SocketChannel sc = null;
          private String host = null;
          private int port = -1;
          public DetectSocketConnection(String host, int port) {
             super(threadGroup, host);
             this.host = host;
             this.port = port;
             System.out.println("DetectSocketConnection::syncObject = " + syncObject);     
          public void run() {
             System.out.println("Scanning " + host + " at port number " + port);
             synchronized(syncObject) {
                try {         
                   InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
                       // Connect
                    sc = SocketChannel.open();
                sc.connect(isa);
                   System.out.println("Found hostname: " + host + "!!!!!!!!!!!!!!!!!!!");
                   hostname = host;
                catch (IOException e) {
                   System.err.println("DetectSocketConnection: " + e.toString());
                finally {
                // Make sure we close the channel (and hence the socket)
                   close();
                   System.out.println("DetectSocketSonnectio: notify()...");
                   syncObject.notify();
          public void close() {
             try {
                if (sc != null) sc.close();
             catch (IOException e) {
       public SocketSearch() {
          sockets = new ArrayList();
        * Add socket to the sockets ArrayList to prepare to start the Socket Search
        * @param host Socket hostname
        * @param port Socket port number
       public void addSocket(String host, int port) {
          DetectSocketConnection detectSocket = new DetectSocketConnection(host, port);
          sockets.add(detectSocket);
        * SocketSearch start method to fire up the sockets threads to search for
       public void start() {
          super.start();
          if (sockets != null) {
             DetectSocketConnection[] arrSockets = (DetectSocketConnection[]) sockets.toArray(new DetectSocketConnection[0]);
             for (int i = 0 ; i < arrSockets.length ; i++) {
                arrSockets.start();
    * Main code to do the socket search
    public void run() {
    try {
    boolean loop = (sockets.size() > 0);
    while (loop) {
    synchronized(syncObject) { 
    System.out.println("SocketSearch.wait() => syncObject = " + syncObject);
    syncObject.wait();
    System.out.println("SocketSearch.wait() => syncObject = " + syncObject + ", finished...");
    if (hostname != null) {     
    // use the hostname
    // you could interrupt the threads now - its your choice
    loop = false;
    else {
    System.out.println("Invalid hostname...");
    ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
    int numThreads = currentGroup.activeCount();
    Thread[] listOfThreads = new Thread[numThreads];
    currentGroup.enumerate(listOfThreads);
    int activeThreads = 0;
    for (int i = 0 ; i < numThreads ; i++) {
    if (listOfThreads[i] instanceof DetectSocketConnection) {
    activeThreads++;
    System.out.println("activeThreads: " + activeThreads);
    if (activeThreads == 0) {     
    // host name is NULL and active threads are finished
    throw new UnknownHostException("Host not found.");
    if (hostname != null) {
    System.out.println("Found hostname: " + hostname);
    // Do something here, use callback to maybe dispose ProgressDialog etc...
    catch (UnknownHostException e) {
    // Do something here, use callback to maybe dispose ProgressDialog etc...
    System.err.println(e.toString());
    catch (InterruptedException e) {
    // Do something here, use callback to maybe dispose ProgressDialog etc...
    System.err.println(e.toString());
    * Test to find a socket from an array of test socket hosts
    public static void main(String args[]) {
    String[] yahooPOP3PossibleSettings = new String[] {
    "yahoo.com",
    "mail.yahoo.com",
    "pop.yahoo.com",
    "pop.mail.yahoo.com",
    "pop3.yahoo.com"
    int PORT_NUMBER = 110;
    SocketSearch socketSearch = new SocketSearch();
    for (int i = 0 ; i < yahooPOP3PossibleSettings.length ; i++) {
    socketSearch.addSocket(yahooPOP3PossibleSettings[i], PORT_NUMBER);
    socketSearch.start();

    Forget it. The Inner class was doing a wait and so was the main thread.
    Not meant to put a wait in the main thread...

  • Java compiler should check if wait() and notify()

    wait(), notify(), and notifyAll() methods should be called within a critical section, but the Java compiler does not check for this. It is usually during running that an Exception is thrown when the methods was not called within a critical section.
    To me, it seems that the compiler should check and enforce that wait(), notify() and notifyAll() be called within a critical section.

    I think I mis-understood you.
    Yes, you are right to say that because callNotify() was called within a critical section at some time, and may be called from other non-critical sections, so the compiler does not have means to keep trace of the calling stack.
    How about this:
    Because critical sections are always marked by the synchronized keyword, the compiler can actually keep count of the synchronized word and its corresponding braces, then when a wait(), or notify(), or notifyAll() call is made at certain point, the compiler just check for the nested synchronized cunt number, if it is non-zero, it will be syntaxically correct.
    Take the example of your code, I see that the proper point for
    public class Test {
      Object lock = new Object();
      public void lockObject() {
        synchronized (lock) {
          callNotify();                     // here the synchronized brace count is 1, so it is OK!
      private void callNotify() {
        lock.notify();               // here the synchronized brace count is 0,
                                            // but because it is a stand alone function, the compiler
                                            // can deliver warning information.
      public void dumbMethod() {
        callNotify();              // should deliver warning
      public static void main(String[] args) {
        Test t = new Test();
        t.lockObject();
        t.callNotify();                   // but here, the synchronized brace count is 0, so failure!
    }

  • About wait() and notify()

    Hello all,
    I have a small problem.Before explaining the problem as such,ill give u a breif description of what i am trying to do
    I have two layers.The upper layer is sender and the lower one is the reciever.Now ,there's only one reciever thread and a number of sending threads.So when one sender sends something...the reciever will start processing with the data.
    In the mean time ,if another sender thread wants to send something to the reciever thread, then it must wait until the reciever enters wait state after it's current processing.
    So the reciever should notify the sender thread which is in wait state...
    My probelm is the sender thread if enters in to wait state once...I'm not able to notify it again when the reciever thread is ready for it.
    Hope some one among u can help me out
    thanking u in advance
    regards
    anees

    you could make the method that does the processing in the receiver, synchronized. that way, the jvm will take care of your requirement.
    if you have to use the wait- notify scheme, then try using notifyAll() instead of notify()

  • Confused about wait()_, notify()

    hey everyone,
    i have a number of executing objects running on independent threads trying to access a single method in a single object. how best can i do this. i am kinda confused. the questions i as myself are should there be a wait and notify in the method that is being called? or is the wait and notify placed in the threads that are trying to call this method.? how do i do this? also when i call notify does it only notify the threads waitin on that particular lock that the notifying thread has locked?
    pleas please help me..

    yeah i see that that i did understand....this is what i am trying to do. i have a single method in an object which is basically a queue. i want multiple other thread to line up on this queue. so this is what i have in my code
    boolean pleaseWait = false;
    public synchronized void getOnLine(Truck t) {
    while(pleaseWait) {
    try {
    wait();
    catch(Exception e) {
    truckLine.enQ(t);
    pleaseWait = false;
    notifyAll();
    but this does not feel right.....i want to know should the above be done in this method or should it be done in the actual thread object that is trying to get on the line. as
    public void run() {
    synchronized(this) {
    while(toAddress.pleaseWait) {
    try {
    wait();
    catch(Exception e) {
    toAddress.getOnLine(this);
    notify();

  • Queues and notifiers - please help?!

    Can someone explain to me how to effectively utilize queues and notifiers? I understand the fundamental difference between the two but I am having a difficult time establishing when I should use one over the other or how to utilize both of them at the same time.
    Essentially what I currently have is a master loop that contains (among other things) an event structure. The event structure contains controls which dictate when notifiers are sent and destroyed. The notifiers “turn on” other loops (all within the same sequence frame as the master loop). These other loops are used for various controls, data logging, etc. Within some of these “sub-loops” I would like to step through a sequence of events – this is where I’m having trouble.
    Here is what I would like to happen: When the user clicks a certain button, a notifier is sent to sub-loop-A and it begins to run. The user then selects from a pull-down menu one of a few different options. Depending on the option selected, a specific set of events occur (whose progress is dictated by both user interaction (pressing buttons) and successful events (data being fed back). I would then like the sequence to “reset” and allow the user to select another option from the same menu – I don’t want to exit all the way back out to the main loop and force the user to re-select sub-loop-A again. However, if from the front panel the user selects sub-loop-B I would like sub-loop-A to exit and sub-loop-B to begin running. I have attached a sample of the basic layout I have so far (in LV 8.2) – I apologize in advance – I’m still learning labVIEW and I’m probably not going about this in the most efficient manner.
    A couple other things to note – I’m trying avoid polling because speed is important. Also, the template I’ve attached is far from complete – it will require additional sub-loops and additional sequence loops (which I have been advised to use que-based state machines - which I'm also not familiar with).
    Any assistance you guys can provide would be great – examples, web links, etc.
    Thanks again!
    -Erik
    Attachments:
    LayoutExample.vi ‏72 KB

    I do see a problem in the operation in that if I hit the stop button, the inner loop of auto starts running like crazy.  I think it is because if the wait for notifier returns an error due to it getting destroyed when the stop button is hit, it still sends out the notifier as the default, which starts the default case structure operating and thus its inner loops.  And they don't stop.
    You should probably get the loops out of the default case.  Any case structure should have a default case that does nothing. 
    A better practice would be in the stop button case, send out a notifier that is for a specific exit case that tells all outer loops to stop.  Then destroy the notifiers.
    In your 4 loops, you have the stop button NOR'ed with the other condition rather than OR'd.  So if you say stop = true, the OR results in a True, but the negation turns that into False and the loop does not stop.  In the top button, you had the enum compared to exit, then that was NOT so the loop would stop immediately if the enum was anything but Exit.  Because the Boolean logic in these loops was convoluted, I think the loops weren't behaving the way they should.
    I made some modifications to clean up the default case and the boolean stop loop logic in each of the loops.  See attached.
    Attachments:
    MultipleLoopsV82 MOD.vi ‏90 KB

  • List of Queues and Notifiers

       Dear Sir/Madam,
    1) I would like to be able to obtain a list of all queues and notifiers in memory. How to do so?
    2) I would like to be able to change the behaviour of the queue. Instead of holding and waiting for an element to be read out of a full queue (when a new element in to be inserted), I would like to be able to push out the oldest element.
    Any suggestions?
    Thanks!
    Regards
    Albert

      Thank you all.
    Thans for the VI, but unfortunately I could not read it (version too high). However, I found "Smart Buffer" and "Recent History" VIs in the "Search Examples". Unfortunately, these are not applicable since I need to generate the queues and notifiers in undefined number of instances.
    What I eventually did:
    1) I would like to be able to obtain a list of all queues and notifiers in memory. How to do so?
    Used a functional global variable VI which stored the names, as well as created/destroyed queues.
    2) I would like to be able to change the behaviour of the queue. Instead of holding and waiting for an element to be read out of a full queue (when a new element in to be inserted), I would like to be able to push out the oldest element.
    I used notifiers:
    a) I call a VI that returns the status of the notifier, and I read all the available notifiers from it.
    b) I append the new data to the one obtained from the notifier, and cut the result to limit the length of this "buffer".
    c) I call a Send Notifier VI, which puts the new data set into the notifier.
    This way is possible but uncomfortable...
    DEAR NI Tech Support,
    Please respond to the questions, and let me know, if there are more elegant solutions (e.g. reading a property node for the list of queues or notifiers, or writing a property node for setting the behaviour of the queue).
    Thanking you in advance.
    Sincerely
    Albert Lysko
    Message Edited by alysko on 12-10-2007 06:48 AM

Maybe you are looking for

  • Updating tables in logical standby database

    Dear DBAs, Is it possible to update non replicated tables in the logical standby database, but have the same schema name? "Alter session disable guard" works only for the current session, in fact i want it for all connected users whithout stopping th

  • Error in invoice due date

    Hi all, i need to fetch invoice due date data(FAEDT) using the FM 'DETERMINE_DUE_DATE'.i passed ZFBDT(base line date) and ZTERM(payment terms) and fetching the invoice due date. DATA : ZFBDT TYPE DATS,        ZTERM TYPE BSAK-ZTERM,        FAEDT TYPE

  • WEP key for Cisco 2100

    Hi I am having a lot of trouble trying to set a WEP, or any other key. When I am visiting 192.168.100.1 there is no option for log in or anything, only observe. The pages 192.168.0.1, 192.168.1.1 & 192.168.2.1 also time out every time. When I ping, t

  • For some reason Firefox is not opening up any pdf files, do you have any suggestions on how to current this problem.

    When I go to a website and they have a pdf file to download, Firefox will not open it. I have to go Internet Explorer to open the pdf file. Do you have any suggestions because I prefer to use Firefox.

  • What are the most important features of the operating system of mac os x?

    I want to know what the important features of Mac OS X is. I'm a Windows person and would like to know the important features of the operating system. I'm thinking of getting a mac but not too sure if it's better than windows.