End threadmeme

The output above shows that when we use a volatile boolean flag, we do not run into infinite loops. This is because the volatile variable directly stored in the main memory. In other words, changes made by one thread are visible to other threads. Thus using volatile makes our code, thread safe.

A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads. But these methods were deprecated by Java 2 because they could result in system failures. Modern ways to suspend/stop a thread are by using a boolean flag and Thread.interrupt() method.

Note: The above code runs into an infinite loop and will give run-time error.The output above shows that the inside thread is never stopped. This happens because the change made to ‘exit’ variable in the main thread is not visible to the inside thread. This is so because the inside thread locally caches the value of exit. To prevent this from happening we can use a volatile variable. The code below illustrates it.

End threadpython

Note: The output may vary every time.By using a flag we can stop a thread whenever we want to and we can prevent unwanted run-time errors.