I have a bit of a problem. I have a java application and when it starts it needs to make around six maybe seven threads that just wait for some sort of event to occur (i.e. user presses a button). An example of how I make these threads is below. The problem is, I open my task manager only to see that all my four cpu cores are at 100% (up from around 20), as soon as I close my application everything returns to normal. I am still new to multi-threading and I know I am committing some sort of concurrency sin here but I would appreciate any insight on how to rectify this situation.
new Thread (new Runnable() { public void run()
{
while (true)
if (doSomeFunction)
{
myFunction();
doSomeFunction = false;
}
} } ).start();
// Somewhere else in the code
doSomeFunction = true;
I am thinking perhaps wait and notify would be the right approch to doing this?
EDIT: Just for clarification, this has nothing to do with powering swing components. Instead this does events based on a script, I don’t want certain script functions to block but instead return immediately while finishing the task in the background.
There are two possible answers here.
The first is that you are waiting for a button press in a Swing application (or similar). If so, threads aren’t the answer. You should simply be using an action listener:
You need to be really careful about using threads in Swing applications. That’s because only one thread (called the Event Dispatching Thread or EDT) is the only thread allowed to make UI updates. All event handlers occur in the EDT. So while code is running on the EDT no UI updates will happen (moving/closing windows, pressing buttons, etc) so EDT code should be short-lived.
The more general problem can be solved in a number of ways that depend on more information than is provided.
Firstly, to answer your question: your CPU usage is going to 100% because the threads are constantly checking the value and calling a function in an endless loop.
You should be using the Java 5+ concurrency model however, which will look something more like this:
As to how to do the inter-thread communication, that’s where it gets tricky. You’re sharing a primitive variable, which is a really bad idea.
The simplest idiom is to use wait-notify:
The
synchronizedmutexes are really important.But Java 5 adds a whole bunch of alternatives to this. I would recommend buying Java Concurrency in Practice and reading it cover to cover.