Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Java Program Error

  Asked By: Francisca    Date: Apr 30    Category: Java    Views: 5679
  

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

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Aylin Kaya     Answered On: Apr 30

1 - what you've explained is not exactly what you've written
2 - for such a simple flow you're code is a bit confusing - I'm talking about the notify + while on the repeatable object and wait - the logic might be correct but its confusing to follow
3 - do you ever set "b1" to true during the flow?
4 - you are waiting on an object (b1) that is set to "false" during paint and never set to true again so basically your while is skipped
5 - ?

 
Didn't find what you were looking for? Find more on Java Program Error Or get search suggestion and latest updates.




Tagged: