Threads

R

repairman2003

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
 
I

Ingo R. Homann

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
 
K

Knute Johnson

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

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);
}
}
 
P

Patricia Shanahan

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

if (!runFlag) {

**** Point A ***** (see below)
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ie) {
// wait is interruptible
ie.printStackTrace();
}
}
}
}
} ....
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
runFlag = true; // so it will run again
synchronized (lock) {
lock.notifyAll();
}
}
});
....

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);
}
}
 
R

repairman2003

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!
 
K

Knute Johnson

Patricia said:
Knute Johnson wrote:
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.

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);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

synchronizing 2 threads 5
Java Threads 2
Thread program 9
threads and shared objects 7
Mutex 4
Understanding java.lang.Object.wait() 7
Error with server 3
Multithreading problem 6

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top