The Java code demonstrates how to use the suspendThread() and resumeThread() methods to manually suspend and resume a thread's execution. However, it's important to note that these methods are deprecated in Java because they can lead to potential thread deadlocks and other synchronization issues. They are not recommended for modern applications.
Instead of using suspend() and resume(), a more appropriate approach would be to use modern thread synchronization mechanisms such as wait() and notify() or higher-level concurrency utilities provided by Java, like the java.util.concurrent package. Here's a brief explanation of how the code works:
As mentioned earlier, using suspend() and resume() methods is discouraged in modern Java programming. Instead, consider using safer and more reliable thread synchronization mechanisms provided by the Java platform. For example, you can use wait() and notify() or explore higher-level abstractions like the java.util.concurrent package that offer thread-safe constructs. These mechanisms provide better control over thread synchronization and help avoid potential pitfalls associated with direct thread suspension.
public class SuspendResume { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); try { Thread.sleep(1000); // Sleep for 1 seconds } catch (InterruptedException e) { e.printStackTrace(); } myThread.suspendThread(); // Suspend the thread try { Thread.sleep(1000); // Sleep for 1 seconds } catch (InterruptedException e) { e.printStackTrace(); } myThread.resumeThread(); // Resume the thread } static class MyThread extends Thread { private volatile boolean suspended; public void run() { while (true) { System.out.println("Thread is running"); try { Thread.sleep(1000); // Sleep for 1 second } catch (InterruptedException e) { e.printStackTrace(); } while (suspended) { Thread.yield(); } } } public void suspendThread() { suspended = true; } public void resumeThread() { suspended = false; } } }
Thread is running Thread is running Thread is running Thread is running Thread is running Thread is running Thread is running Thread is running ......
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions