Synchronization is required for reliable communication between threads as well as for mutual exclusion.
Do not use Thread.stop(deprecated and inherently unsafe), a recommended way to stop on thread from another is to have the first thread poll a boolean field that is initially false but can be set to true by the second thread to indicate that the first thread is to stop itself.
// Broken! - How long would you expect this program to run? (loop forever: liveness failure)
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested) i++;
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
// Properly synchronized cooperative thread termination
public class StopThread {
private static boolean stopRequested;
private static synchronized void requestStop() {
stopRequested = true;
}
private static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String[] args) throws InterruptedException {
....requestStop();
}
}
Synchronization has no effect unless both read and write operations are synchronized.
// Cooperative thread termination with a volatile field
public class StopThread {
private static volatile boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
....
}
The volatile modifier performs no mutual exclusion, it guarantees that any thread that reads the field will see the most recently written value.
// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
return nextSerialNumber++;
}
One way to fix the generateSerialNumber method is to add the synchronized modifier to its declaration, better still, use the class AtomicLong, which is part of java.util.concurrent.atomic. It does exactly what you want and is likely to perform better than the synchronized version.