views:

422

answers:

2

Hello,

I have an assignment with threads and I cant have the threads go into busy wait state. How do I know if a thread is in blocking state or in busy wait? Is there a command that checks it?

In the program I have 2 matrices and I need to transform them. So I have a transform thread and the code is as follows:

transformThread transformThreadFirst = new transformThread(firstMat, n);
transformThread transformThreadSecond = new transformThread(secondMat, n);

transformThreadFirst.start();
transformThreadSecond.start();

try
{
 transformThreadFirst.join();
 transformThreadSecond.join();
}
catch(InterruptedException e)
{
}

Any of the threads will be in busy wait or is it ok? Or you have a better solution? Also in the run of the transformThread I do not use any yield, just 2 for loops and thats it, just the transform action..

Thanks in advance,

Greg

A: 

There's a jstack utility. use it as jstack <pid>, passing the process id of your running jvm. It would display what every thread in that app is doing, together with thread status (RUNNING, WAITING, BLOCKED).

It is bundled with JDK and located in its bin/

alamar
+4  A: 

Busy waiting is doing something repeatedly until another operation finishes. Something like this:

// The next line will be called many many times
// before the other thread finishes
while (otherThread.getState() == Thread.State.RUNNABLE) {}

So your code is not busy waiting, the current thread will block until the transformThreadFirst finishes and then block until transformThreadSecond is done.

soulmerge
So in general can I use the "join()" command without fear that I may busy wait another thread?
Yes, join() will block the current thread, which is the correct way of waiting for something to happen.
soulmerge
@Greg - I agree with soulmerge's explanation that join() is the correct approach, but for your benefit greg, realize that one thread can't cause ANOTHER to busy wait, it is more your OWN thread's behavior that does that. Any type of loop that checks a flag is a busy wait, while any command that blocks is not. In summary: You can't make somebody ELSE busy wait, only yourself.
Kevin