Help with Threads. - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Help with Threads.

atchatch Posts: 1Member
Hi guys, I have two classes A and B.
[code]
import java.util.Random;


public class Commander_1 extends Thread
{

private final String[] QUESTIONS =
{
"How old are you?",
"How many fitness tests have you taken?",
"Are you prepared for the war?"
};
private int nextQuestion = 0;
private boolean waitingForAnswer = false;

private synchronized void setWaitingForAnswer(boolean value)
{
waitingForAnswer = value;
}

public synchronized boolean isWaitingForAnswer()
{
return waitingForAnswer;
}

public synchronized void sir()
{
waitingForAnswer = false;
}

private int setNextQuestion()
{
return new Random().nextInt(3);
}

private synchronized void askQuestion()
{
while (isWaitingForAnswer())
{
try
{
wait();
}
catch (InterruptedException e)
{ }
}
nextQuestion = setNextQuestion();
System.out.println("Commander (Q" + (nextQuestion + 1) + ") " + QUESTIONS[nextQuestion]);
setWaitingForAnswer(true);
notifyAll();

}

public synchronized int getNextQuestion()
{
return nextQuestion;
}

@Override
public void run()
{
for (int i = 0; i < 3; ++i)
{
askQuestion();
try //WITHOUT THIS TRY BLOCK CODE WONT WORK. WHY?
{
Thread.sleep(500);
}
catch(InterruptedException e)
{

}
}
}
}


public class Soldier_1 implements Runnable
{

private final String[] ANSWERS =
{
"25",
"2",
"All of us are sir!"
};
private int nextAnswer = 0;
private Commander_1 myCommander;

Soldier_1(Commander_1 commander)
{
myCommander = commander;
}

private synchronized void answerQuestion()
{
while (!myCommander.isWaitingForAnswer())
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
if (myCommander.isWaitingForAnswer())
{
myCommander.sir();
nextAnswer = myCommander.getNextQuestion();
System.out.println("Soldier (A" + (nextAnswer + 1) + ") " + ANSWERS[nextAnswer]);
notifyAll();
}
}

@Override
public void run()
{
for (int i = 0; i < 3; ++i)
{
answerQuestion();
try //WITHOUT THIS TRY BLOCK CODE WONT WORK. WHY?
{
Thread.sleep(500);//IF I CHANGE THIS VALUE TO BE DIFFERENT
}//TO THE VALUE IN PREV. CLASS IT ALSO FREEZES.
catch(InterruptedException e)
{

}
}
}
}
[/code]
Thanks for any help with this problem.
Sign In or Register to comment.