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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

add a time period of delay in main thread.

Status
Not open for further replies.

wminghao

Programmer
May 29, 2000
24
US
Hi, all:

I met a problem while executing the following code.

I need to check the vector to see if it is empty, if yes, remove the first element and process it. else go to the loop again.

While(true){
if(myVec.isEmpty()==false){
myObject=(myObject)myVec.remove(0);
//next process the object here
...
}
//else do nothing
}


But the problem is that in the while loop, it hangs there and never goes to the next loop.

After I added a time period of delay() in the loop, after if, everything is working now.

void delay(){
for(int i=0;i<1000;i++)
for(int j=0;j<1000;j++)
;
}

My question is that,
1) why does this cause a problem?
2) In multithreading, I can add sleep() in the thread run(), but this is a main thread, so there is no sleep here, my delay function is CPU entensive, very bad in fact, is there any better way to solve this?

Thanks so much!!!


 
I think the problem is that the loop is a infinity loop
While(true)
{
}

You should use:
boolean jobFinished = false;
While(!jobFinished)
{
if(myVec.isEmpty()==false)
{
...
}
else
{
jobFinished = true;
}
}
use a for loop with greater counter here consume more resource because it loops more than necessary.
 
Hi,
Prosper is right about the infinite loop. I would like to tell u that u can have a thread's sleep method in ur main method as well.. u will have to do this.
// get the currently executing thread.
Thread mainThread = Thread.currentThread();
// make it sleep for how much ever u want to
mainThread.sleep(//whatever delay u want);
and dont forget to put these two statements within a try catch block..

Hope this helps,
Reddy316
 
But in my program, I run it as RMI server. The RMI client runs and add message into the vector.

I need this infinite loop, so everytime I check the Vector to see if it is empty or not, if it is empty, process it.

My question is, checking the Vector is blocking operation?
The loop cannot execute, what is the reason?
 
I know the reason now.

It is due to the process of message.
I am trying to establish peer to peer communication between two nodes.

In the process message of the RMI Server, after done, it will call the RMI Client remote method, which will block the thread from running until this RMI Call is done. So it hangs there forever.

Thanks so much for all ur help!

If any questions, drop a message.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top