How to Stop a Thread

There is no direct method to stop a thread. Earlier there used to be methods like Thread.stop(), however now these are deprecated. So how can we stop a thread if there is no 'stop' method?

To understand the answer, we first need to understand the thread and its working. For understanding the thread, please refer to other post 'What is Thread'. So one thread performs a assigned work at a time and its life is over once this work is done. Like if we take example quoted in 'What is Thread' post, then a painting work assigned to a sub-contractor is the life of relation with him. As soon as, he will complete his painting work, the sub-contracting relation will end. 

So the right way to stop a thread is to complete its work, or to make it understand that its work is over and it has to exit. For example, Painting contractor can ask the sub-contractor painter while assigning the job that please work till you finish painting in this service or till I call you to come out of this room. So the sub-contractor will start painting and will automatically exit from the relation as soon as it will finish the painting. Alternatively Painting Contractor can call him in-between and so the sub-contractor will keep on checking that whether the contractor is calling him or not. If not, he will continue with his work till its completion. If yes, he will leave the work and exit the room. 

What is Thread

A thread is a fork of a computer program in two or more concurrently running tasks. Let us try to understand it with example, 
  • Process: It is generally a single program in computer. Like, You need to get your house painted. So you hire a painting contractor and make a contract for painting your house. Now this painting contractor will get the house painted. So we can equate it with a process which, once start, will paint the home. Suppose you also want to change the flooring of your home, then you will hire some other contractor for this work. This will be another process which will do the flooring work. 
  • Threads: Now if the painting contractor paint the whole house himself single handedly, it will take him many days. But he as well as you want to get your work done ASAP. The solution is that contractor uses multiple sub-contractor under his control and use them to paint the house. These sub-contractors work simultaneously on different portion of the tasks. These sub-contractors can share the resources, i.e. will be using the resources from same pool. Now as multiple sub-contractors are working in parallel on multiple tasks, it will speed up the whole process and whole house will be painted in much lesser time. So these multiple sub-contractors are like threads in main process (painting contract).