Sign in to follow this  
johnnyBravo

Java, is starting and stopping a thread like this ok?

Recommended Posts

In my program I've got an animated map(has a while loop) that runs on a separate thread, and to stop it, i set a flag in animated map so it will exit its while loop. Then to start the thread again, I create a new thread and start it. Could there be any problems with doing it this way? Also how do I pause a thread so I can update some shared variables and then resume again? (aka being thread safe) thx

Share this post


Link to post
Share on other sites
Quote:
Original post by johnnyBravo
In my program I've got an animated map(has a while loop) that runs on a separate thread, and to stop it, i set a flag in animated map so it will exit its while loop.


That's fine. Generally, you'll want to declare the flag as volatile:


public class MyClass implements Runnable
{
private Thread thread = null;
private volatile boolean running = false;

public void start()
{
if(thread != null) return;

thread = new Thread(this);
thread.start();
}

public void run()
{
running = true;
while(running)
{
...
}
}

public void stop()
{
running = false;
thread = null;
}
}



Using this approach, if the object can be manipulated from multiple threads, you'll want to synchronize the start and stop methods to make manipulation of the thread object thread-safe.

Quote:
Then to start the thread again, I create a new thread and start it.


That's fine, but keep in mind that creating threads has a certain amount of overhead. If you do it frequently, you can hurt performance. In that case, you want might want to consider a thread pool.

A better option would be to use an instance of java.util.concurrent.ExecutorService. This will manage a thread pool for you. You can configure one to run the same task repeatedly at different intervals, or as frequently as you feed tasks to it.

Quote:

Also how do I pause a thread so I can update some shared variables and then resume again? (aka being thread safe)


That's not being thread-safe, it's being inefficient. To safely update shared data, use synchronization.

Share this post


Link to post
Share on other sites
Thank you,


From what I've read so far, I think to synchronize I just need to add the 'synchronized' keyword in front of the functions?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this