Developer community
0 votes
asked by Guru (24.6k points) 30 54 84 | 39 views

2 Answers

0 votes
Ans). First of all , we should create a boolean type variable which stores ‘ false’ . When the user wants to stop the thread. We should store ‘true’into the variable. The status of the variable is checked in the run ( ) method and if it is true, the thread executes ‘return’ statement and then stops.
answered by Guru (39.1k points) 10 22 36
0 votes


In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.
Often a volatile boolean field is used which the thread periodically checks and terminates when it is set to the corresponding value.
I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.
answered by Expert (13.2k points) 27 43 61

Related questions

0 votes
2 answers
asked by smith Geek (15.3k points) 17 43 67 | 19 views
0 votes
1 answer
asked by smith Geek (15.3k points) 17 43 67 | 12 views
0 votes
2 answers
asked by smith Geek (15.3k points) 17 43 67 | 38 views
0 votes
1 answer
asked by sunny Expert (11.4k points) 14 23 30 | 19 views
0 votes
1 answer
asked by sara Guru (24.6k points) 30 54 84 | 25 views
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers


10.7k users

3,754 questions
4,046 answers
10,709 users