Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

multithreading - How to kill a thread immediately from another thread in java?

is there anyway to kill a thread or interrupt it immediately.
Like in one of my thread, i call a method which takes time to execute (2-4 seconds). This method is in a while(boolean flag) block, so i can interrupt it from the main thread.

But the problem is, if i interrupt it; it will wait till the executing loop is finished and then on next conditional check, it will stop execution.

I want it to stop right then. Is there anyway to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you need the thread stop earlier you need to put more break points in your thread.

You can use stop() to styop it immediately, but this comes at a cost and has many possible undesirable side effects. You can use stop() safely with great care, but in reality you will find it simpler/easier/safer to put in more break points (points where you check if the thread should stop)

BTW, If you want to throw an error which won't be printed you can ThreadDeath as this can shutdown the thread silently.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...