Developer community
0 votes
39 views
asked by Guru (24.6k points) 32 58 93 | 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) 11 24 38
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) 29 44 63

Related questions

0 votes
2 answers
asked by smith Geek (15.3k points) 19 43 69 | 19 views
0 votes
1 answer
asked by smith Geek (15.3k points) 19 43 69 | 13 views
0 votes
2 answers
asked by smith Geek (15.3k points) 19 43 69 | 39 views
0 votes
1 answer
asked by sunny Expert (11.4k points) 16 23 32 | 20 views
0 votes
1 answer
asked by sara Guru (24.6k points) 32 58 93 | 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

Categories


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

3.8k questions

4k answers

117 comments

10.7k users

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