I am trying to understand Threads, so I wrote some code that I will play around with because the best way to learn for me is by experimenting...... Anyway, I have 2 text fields each with a counter in them. The counters are each in there own run method. I want to be able to stop and start them with 2 ActionListeners attached to 2 Buttons. When I run the program, the ActionListeners are not doing their job. Is it because the run methods are in an endless loop? How can I fix this problem? Thanks in advance!!! Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test9099 extends
Thread {
int counter1 = 0;
TextField field1;
TextField field2;
Thread t,c;
JButton pauseButton;
JButton resumeButton;
Test9099()
{
JFrame theFrame = new JFrame();
field1 = new TextField(10);
field2 = new TextField(10);
pauseButton = new JButton("Pause");
resumeButton = new JButton("Resume");
pauseButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("Pause Button Pressed");
try
{
t.wait();
c.wait();
}
catch (InterruptedException ie)
{
}
}
});
resumeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t.notify();
c.notify();
}
});
Container c = theFrame.getContentPane();
c.setLayout(new BorderLayout());
c.add(field1,"East");
c.add(field2,"West");
c.add(pauseButton,"North");
c.add(resumeButton,"South");
theFrame.setSize(400,400);
theFrame.show();
t = new Thread(this);
t.start();
}
public synchronized void run()
{
while (true)
{
counter1++;
String str = "" + counter1;
field1.setText(str);
System.out.println(str);
try
{
c.notify();
}
catch (Exception e)
{
e.printStackTrace();
}
t.yield();
}//end of while
}//end of run
class Inner extends Thread
{
public Inner()
{
c = new Thread(this);
c.start();
}
public synchronized void run()
{
while(true)
{
int counter2 = counter1++;
String g = "" + counter2;
field2.setText(g);
try
{
c.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}//end of while
}//end of run()
}
public static void main(String[]args)
{
Test9099 a = new Test9099();
Test9099.Inner b = a.new Inner();
}
}