Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

Threads

Thread view: 
repairman2003@gmail.com - 07 Mar 2007 07:23 GMT
I'm having some trouble understanding how to set up a thread to pause
execution when some other thread meets some condition.  I'm using a
base class and then at least 2 classes that extends Thread.  The
threads don't share any data among each other, just between the thread
and the base class.  The baseClass just starts the other threads and
outputs information to the screen.  For some background this is a
robotics project so the threads are moving the robot and reading
data.  If certain threads aren't paused they will conflict with each
other.

Here is a basic view of the classes:

public class baseClass
{
    thread1 thread1Obj = new thread1();
    thread2 thread2Obj = new thread2();
    ....

    void upDateScreen()
    {
         thread1Obj.start();
         thread2Obj.start();

         while(true)
        {
            //output things to screen
        }
    }
}

class thread1 extends Thread
{
    int x = 0;

    void run()
    { //At the present moment, everything inside the run() is in an
infinite loop.  This can change if necessary

         //Read x in from a sensor
         if(x<10)
             //Pause all other threads so this one can do what it
needs to do
         ...
    }
}

class thread2 extends Thread
{
    void run()
    {
         ...
    }
}

How do I set it up so that thread2 is paused while thread1 is doing
something important?

Thanks
Ingo R. Homann - 07 Mar 2007 09:24 GMT
Hi,

Ever heared of the keyword "synchronized"? wait()? notifyAll()?

If not, read a tutorial about that! (Giving you a short example will not
really be helpful, I suppose...)

Ciao,
Ingo
Knute Johnson - 07 Mar 2007 17:19 GMT
> I'm having some trouble understanding how to set up a thread to pause
> execution when some other thread meets some condition.  I'm using a
[quoted text clipped - 54 lines]
>
> Thanks

There are a million ways to do that.  The perfect solution for this
problem would be a semaphore.  If you are using 1.5 or later there is a
Semaphore class in the API.  If not you could use a flag and
wait/notify.  wait/notify is very confusing or at least I found it so.
A few years ago I had a similar problem and asked on this group for a
simple example of wait/notify but was told to go read a book.  Well I
had the book and it didn't help that much.  I would have given my eye
tooth for a simple example.  Look at the program below for a simple
implementation of wait/notify.  The program starts several threads and
they run until the runFlag is set to false.  Set the runFlag false by
pressing the 'Stop' button.  Then they go into a synchronized section
and block on the wait() until you press the 'GO' button.  The 'GO'
button has a synchronized section that calls notifyAll() on the lock.
This allows all threads to start again.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test8 implements Runnable {
    static volatile boolean runFlag = true;  // only one of these
    int name;
    static Object lock = new Object();  // only one of these too

    public test8(int name) {
        this.name = name;

        new Thread(this).start();  // start thread when created
    }

    public void run() {
        while (true) {
            System.out.println(name);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) { }

            if (!runFlag) {
                synchronized (lock) {
                    try {
                        lock.wait();
                    } catch (InterruptedException ie) {
                        // wait is interruptible
                        ie.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                // make 8 test8s and name them 0 - 7
                for (int i=0; i<8; i++) {
                    new test8(i);
                }

                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLayout(new FlowLayout());

                JButton b = new JButton("Stop");
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        runFlag = false;
                        System.out.println();
                    }
                });
                f.add(b);

                b = new JButton(" GO ");
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        runFlag = true;  // so it will run again
                        synchronized (lock) {
                            lock.notifyAll();
                        }
                    }
                });
                f.add(b);

                f.pack();
                f.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}

Signature

Knute Johnson
email s/nospam/knute/

Patricia Shanahan - 07 Mar 2007 18:10 GMT
...
>     public void run() {
>         while (true) {
[quoted text clipped - 4 lines]
>
>             if (!runFlag) {

**** Point A ***** (see below)

>                 synchronized (lock) {
>                     try {
[quoted text clipped - 7 lines]
>         }
>     }
...
>                 b.addActionListener(new ActionListener() {
>                     public void actionPerformed(ActionEvent ae) {
[quoted text clipped - 4 lines]
>                     }
>                 });
...

There is a low probability bug in this code. Suppose a worker thread T
runs to Point A, and then gets interrupted. Before T's next time slice,
the event handler thread E runs, and completely executes the
actionPerformed method.

This is possible, because T is not synchronized on lock at point A.

When T gets its next timeslice, it goes into a wait on the lock, without
having checked runFlag since it was changed by E. T is then stuck
waiting for a condition that has already happened.

The following modified version of the program demonstrates this. I have
added some output statements and one sleep, but not changed the
operations on lock or runFlag. To see the effect, click on the "GO"
button less than 10 seconds after clicking "Stop", and then watch for at
least 10 seconds. Changing the length of the added sleep call changes
that time limit.

In the original program the bug is low probability, because each thread
spends most of its time sleeping, and reaches point A very soon after
the start of its first time slice after coming out of a sleep, a period
when it is unlikely to be interrupted. The need for human interaction in
the critical window reduces the number of tests that can be done, as
well as reducing the probability of failure.

However, it should not be used as a pattern for writing multi-threaded
code. In a different context it this structure could have an annoyingly
high failure rate.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test8 implements Runnable {
  static volatile boolean runFlag = true; // only one of these

  int name;

  static Object lock = new Object(); // only one of these too

  public test8(int name) {
    this.name = name;

    new Thread(this).start(); // start thread when created
  }

  public void run() {
    while (true) {
      System.out.println(name);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {
      }

      if (!runFlag) {
        try {
          Thread.sleep(10000);
        } catch (InterruptedException ie) {
        }
        System.err.printf(
            "Thread %s waiting for runFlag true%n", name);
        synchronized (lock) {
          try {
            lock.wait();
          } catch (InterruptedException ie) {
            // wait is interruptible
            ie.printStackTrace();
          }
        }
        System.err.printf("Thread %s restarted%n", name);
      }
    }
  }

  public static void main(String[] args) {
    Runnable r = new Runnable() {
      public void run() {
        // make 8 test8s and name them 0 - 7
        for (int i = 0; i < 8; i++) {
          new test8(i);
        }

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new FlowLayout());

        JButton b = new JButton("Stop");
        b.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            runFlag = false;
            System.out.println();
          }
        });
        f.add(b);

        b = new JButton(" GO ");
        b.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            runFlag = true; // so it will run again
            synchronized (lock) {
              lock.notifyAll();
            }
            System.err.printf("Threads restarted%n");
          }
        });
        f.add(b);

        f.pack();
        f.setVisible(true);
      }
    };
    EventQueue.invokeLater(r);
  }
}
repairman2003@gmail.com - 07 Mar 2007 22:54 GMT
Thank you very much!  I never really got concurrency down pact during
school but this helped out alot.  All the tutorials I found on
concurrency really weren't too much of a help, just needed an example
of how to use it in my own problem.  Cheers!
Knute Johnson - 08 Mar 2007 07:58 GMT
> There is a low probability bug in this code. Suppose a worker thread T
> runs to Point A, and then gets interrupted. Before T's next time slice,
[quoted text clipped - 24 lines]
> code. In a different context it this structure could have an annoyingly
> high failure rate.

Patricia:

Your right!  That was stupid on my part.  The flag check should have
been in the synchronized block to prevent just that sort of thing from
happening.  That will teach me for getting in a hurry.

For the OP, timing is always an issue with wait/notify.  If you call
notify before wait, the waiting threads may wait for ever.

For your problem I like the semaphore solution better anyway.  See the
second example.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test8 implements Runnable {
    int name;
    static boolean runFlag = true;  // only one of these
    static Object lock = new Object();  // only one of these too

    public test8(int name) {
        this.name = name;

        new Thread(this).start();
    }

    public void run() {
        while (true) {
            System.out.println(name);

            synchronized (lock) {
                if (!runFlag) {
                    try {
                        lock.wait();
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                for (int i=0; i<8; i++) {
                    new test8(i);
                }

                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLayout(new FlowLayout());

                JButton b = new JButton("Stop");
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        synchronized (lock) {
                            runFlag = false;
                        }
                    }
                });
                f.add(b);

                b = new JButton(" GO ");
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        synchronized (lock) {
                            runFlag = true;
                            lock.notifyAll();
                        }
                    }
                });
                f.add(b);

                f.pack();
                f.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}

import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import javax.swing.*;

public class test7 implements Runnable {
    int name;
    static Semaphore sem = new Semaphore(8,true);

    public test7(int name) {
        this.name = name;

        new Thread(this).start();
    }

    public void run() {
        while (true) {
            sem.acquireUninterruptibly(1);

            // normal thread processing here
            System.out.println(name);

            sem.release(1);
        }
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                for (int i=0; i<8; i++) {
                    new test7(i);
                }

                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setLayout(new FlowLayout());

                JButton b = new JButton("Stop");
                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        if (ae.getActionCommand().equals("Stop")) {
                            sem.acquireUninterruptibly(8);
                            ((JButton)ae.getSource()).setText(" GO ");
                        } else {
                            sem.release(8);
                            ((JButton)ae.getSource()).setText("Stop");
                        }
                    }
                });
                f.add(b);

                f.pack();
                f.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}

Signature

Knute Johnson
email s/nospam/knute/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.