I know that Thread.stop() and other functions are deprecated, and I want to stop a thread from running if a certain condition is met. Here is a simplified version of what I’m doing now:
public class SomeThread extends Thread
{
private static boolean running = true;
public static void shutdown()
{
running = false;
}
public void run()
{
while( running )
{
// do something cool
}
return; // <- this is what I'm wondering about
}
}
When another class calls SomeThread’s shutdown() method, the while loop exits, and then the run() method returns. Is this safe?
The main reason I’m using a while loop instead of just letting run() do the work is because there are a few things I only want to do once (before the while loop), and I’m really only using the thread for concurrency. I’m sure this is a bastardization of what Threads were meant for, but I’m mainly just wondering about the return statement.
The return is fine, the rest of your code is iffy.
The
runningmember should either be volatile, or you need some synchronization around the reads and writes to that variable.(Having
shutdownandrunningas statics is unusual.)