Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting rid of infinite looping

Status
Not open for further replies.

kohinoor2007

Programmer
Mar 21, 2007
69
0
0
DE

Hi guys,

Have a situation in which I have a function called "Test()"as shown below.It has to wait until a flag becomes "1".
So Iam running it in an infinite loop until the flag becomes "1".

The "Test()" function is running in one thread.

Have another function called "eventListener"(See Below), which changes the flag to "1". This function gets called from another thread.


This works....

But I want to get rid of this infinite looping mechanisam because it is running the processor time...
Don't want to use the "sleep" or "join" stuffs to make the thread sleep..

Is there any elegant way of handling this. May be like some mutexes.....

Would be nice if someone could show what should be done in the following code to achieve that....

Thanks

Code:
//Flag
private AtomicLong imageIndicator;

imageIndicator.set(-1);

public void Test()
{

while(imageIndicator.get()==-1)
{
  //Run in infinite loop.
}
if(imageIndicator.get()==1)
{
 //Do something.
}

}
				


public void eventListener(){
		
	imageIndicator =1;		
}
 
Why don't you want to use sleep?
At least it's better than your approach.
Whether 10, 100 oder 1000 ms Sleeptime is appropriate is up to you:
Code:
 public void Test ()
{
	while (imageIndicator.get ()==-1)
	{
		try 
		{
			Thread.sleep (100);
		}catch (InterruptedException ignored) {}
	}
	if (imageIndicator.get ()==1)
	{
		//Do something.
	}
}

But why doesn't your eventListener call
// Do something
himself?

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top