+ 6
Qus:-How to stop a thread in java? Explain about sleep () method in a thread?
3 odpowiedzi
+ 1
what do you mean by stop thread??
+ 1
sleep(1000) that makes your thread to sleep or wait for 1000milli seconds(1sec) before processing.
+ 1
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.
Using a volatile boolean flag: We can also use a volatile boolean flag to make our code thread safe. A volatile variable is directly stored in the main memory so that threads cannot have locally cached values of it. A situation may arise when more than one threads are accessing the same variable and the changes made by one might not be visible to other threads. In such a situation, we can use a volatile boolean flag.