I have one problem in thread programming.
I have developed program in which one thread
increment by one and the other should decrease
by one. Thereafter they should display on the screen
. However, on the screen number is incremented twice and
decremented twice and not one by one
Can anyone suggest to do it ?
import java.applet.*;
import java.awt.*;
public class AnimationApplet15 extends Applet implements Runnable
{
Thread th1,th2;
private Image im = null;
private boolean animate = true;
boolean b1,b2;
int n1,n2;
public AnimationApplet15()
{
}
public void init()
{
resize(500, 250);
im = createImage(500,250);
b1=true;b2=false;
n1=40;n2=0;
}
public void paint(Graphics g)
{
if ( im!= null)
g.drawImage(im, 0,0, null);
}
public void start()
{
if (th1== null)
{
th1 = new Thread(this);
th1.start();
}
if (th2== null)
{
th2 = new Thread(this);
th2.start();
}
}
public void stop()
{
if (th1!= null)
{
th1.stop();
th1= null;
}
if (th2!= null)
{
th2.stop();
th2 = null;
}
}
public void run()
{
// Get an instance of java.awt.Graphics to draw on image
Graphics display = im.getGraphics();
// Set font for display
Font textFont = new Font("Arial", Font.PLAIN, 20);
display.setFont(textFont);
display.setColor (Color.yellow);
display.fillRect (0,0, 500, 250);
display.setColor (Color.gray);
while (true)
{
if(b1 == true)
{
try
{
synchronized(this)
{
display.setColor (Color.yellow);
display.fillRect (0,0, 500, 250);
display.setColor (Color.gray);
n1--;
display.drawString ("Value of First
Number: "+n1, 100, 100);
display.drawString ("Value of Second
Number: "+n2, 150, 150);
repaint();
th1.sleep(1000);
}
b1 = false;
b2= true;
wait();
notify();
}catch(Exception e) {}
}
if(b2 == true)
{
try
{
synchronized(this)
{
display.setColor (Color.yellow);
display.fillRect (0,0, 500, 250);
display.setColor (Color.gray);
n2++;
display.drawString ("Value of First
Number: "+n1, 100, 100);
display.drawString ("Value of Second
Number: "+n2, 150, 150);
repaint();
th2.sleep(1000);
}
b1= true;
b2 = false;
wait();
notify();
}catch(Exception e) {}
}
}//end of while
}
}