Here is the problem. I attempted but two thread not run successfully
can anyone me.
Create 2 Thread classes.One Thread is Incrementor and has
one variable cnt1 with initial Value 0. Incrementor thread
increments value of cnt1 by 1 each time. The other thread is
Decrementor which has variable cnt2 with initial value 100.
Decrementor thread decrements value of cnt2 by 1 each time.
- Incrementor thread increments value of cnt1 by one and
notifies the other thread about this value
- The decrementor thread decrements value of its variable
cnt2 by one and compares values of cnt1 and cnt2. If values of cnt1
and cnt2 are different then notifies the Incrementor thread and above
mentioned step is repeated.
- But if values of cnt1 and cnt2 are matching then
following message is displayed
Matching Value : 50
import java.awt.*;
import java.applet.*;
public class increment extends Applet implements Runnable
{
int incr,decr;
Thread th1,th2;
boolean b1 = true;
boolean b2 = true;
public void init()
{
incr =0;
decr = 50;
}
public void start()
{
th1 = new Thread(this);
th1.start();
th2 = new Thread(this);
th2.start();
}
public void run()
{
while(b2)
{
//b1=false;
try
{
th2.sleep(100);
decr -= 2;
repaint();
notify();
synchronized(this)
{
while(b1)
wait();
}
}catch(InterruptedException e) {}
}
while(b1)
{
try
{
th1.sleep(100);
incr += 1;
repaint();
b2 = true;
notify();
synchronized(this)
{
while(b2)
wait();
}
}catch(InterruptedException e) {}
}
}
public void stop()
{
b1 = false;
b2 = false;
}
public void paint(Graphics g)
{
g.drawString("Value is:" +incr +"decr :="+decr,200,200);
if(incr == decr)
{
g.drawString("Value have matched: incr=" +incr
+ "decr: "+decr,200,250);
b1 = false;
b2 = false;
}
}
public void update()
{
repaint();
}
}