Java 에서 thread.Interrupted 메소드를 사용해야 하는 이유
Why we should use interrupt method in java
Why we should check thread was interrupted in multi-thread programming?
For Example, Can you expected result to this code?
![](https://blog.kakaocdn.net/dn/oxR4K/btrHOsObdWy/oYN6tWwz85Sifau4IlilHK/img.png)
When execute code, Thread start sleeping for 10000000 mils. And Main Thread is blocking by Other Thread. The application will not stop. So, we should kill sleeping Thread. In Java, we have two method to kill thread.
- call Interrupted()
- call stop() (it’s deprecated so we aren’t handle this)
What is Interrupt Thread?
Interrupt Method is raise an exception at interrupted thread. Why raise exception? Because, we should teardown(release resource) in interrupted thread. Look at the code below.
![](https://blog.kakaocdn.net/dn/POyI6/btrHOcY6RIy/1KYEQlGhPxxNG5ZB5Tg8K0/img.png)
When the thread was interrupted, It doesn’t change the value of isActiveConnection to true. So, The other thread raise IllegalAccessException when they use this datasource. So, we should change the value is true.
Return Resources using Interrupted Exception
As i said before, interrupt method is raise exception at target thread. So we use this. Look at the code below.
![](https://blog.kakaocdn.net/dn/w7O3y/btrHNMzY5vW/epcG2vyvjFBQyzm8QPqqqk/img.png)
![](https://blog.kakaocdn.net/dn/1p0B9/btrHN2oZIgy/HpSZlDFzNKLYkUMkPMhIvK/img.png)
We used try..catch expression for changing dataSource activeConnection status to false. This is why we use interrupt method when need to kill thread. How did if we used thread.stop method?
Use Thread.stop Method
This chapter we use stop method for kill thread. Look at the code below.
![](https://blog.kakaocdn.net/dn/teEkT/btrHPPaMROz/uc4mSIY9cTtkmj67zTkn7k/img.png)
We just change interrupt method to stop method. Can you expect that result?
![](https://blog.kakaocdn.net/dn/bh2voR/btrHOTY8W3P/51UdEMhc9QkFCmkHmpHwG1/img.png)
It’s not return resource (isActiveConnection). Because the stop method is just forcing kill thread. Not raise InterruptedException. So, we don’t use stop method in java.
Finally
This is why we should use interrupted method in java. Please do not use stop method. Stop method is deprecated in oracle java. If post is helpful to you, please subscribe me.
내 영문 블로그
https://medium.com/@dev0jsh/why-we-should-use-interrupt-method-in-java-61fffab0d231