Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of stopping Thread safely in java

Shulou Source: shulou.com Published: 2022-06-03 13:43:40 09月22日 Update

This article mainly introduces "the method of java safe stop thread". In the daily operation, I believe that many people have doubts about the method of java safe stop thread. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "java safe stop thread method". Next, please follow the editor to study!

Thread.stop () is an obsolete method that is not recommended because the stop method is too violent, forcibly terminates a thread in the middle of execution, and immediately releases all locks on that thread. Will break the consistency of the reference object in the thread.

Interrupt the thread using the method of judging flag bits

Interrupt () / / Thread interrupt (flag bit is set to true) isInterrupted () / / determines whether it is interrupted interrupted () / / determines whether it is interrupted, and clears the current interrupt status (flag bit changed to false) public static class TestThread extends Thread {public TestThread (String name) {super (name);} @ Override public void run () {String threadName=Thread.currentThread (). GetName () In while (! isInterrupted ()) {/ / Runnable, use Thread.currentThread (). IsInterruputed System.out.println (threadName+ "is run");} System.out.println (threadName+ "flag is" + isInterrupted ());}} public static void main (String [] args) throws InterruptedException {Thread testThread=new TestThread ("test"); testThread.start (); Thread.sleep (2000); testThread.interrupt ();}

When an InterruptedException exception is thrown, the thread interrupt flag bit will be reset to false, and the thread will not be interrupted normally, so it is necessary to manually interrupt interrupt ()

At this point, the study on "java safe method to stop threads" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Threads methods safety flags learning more help utility consistency next consistency usage cause object manual article violence state theory knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Apple vpn MySQL OPPO Reno