That's right, so java cannot get rid of the thread, the thread just starts until it terminates. So: To get rid of a thread, you need to enable the method to start threads, and then get rid of all references to Thread and any Runnable with which it is designed.
You want to include the finishing thread, a simple example:
class SimpleRunnable implements Runnable { public volatile boolean run = true;
Creating a thread from this runnable:
SimpleRunnable run = new SimpleRunnable(); Thread thread = new Thread(run); Thread.start(); //run thread //Stop thread run.run=false; //Thread will be removed when out of scope
You need to create a Runnable for each user in your case, and then call to set a stop variable when creating a new thread. For example, you can store each runnable in ConcurrentHashMap by userId.
ConcurrentHashMap<String,SimpleRunnable> runnablesByUser = new ConcurrentHashMap<>(); public void startNewThreadForUser(String userId){ //Time passes, retrieve and kill old thread: SimpleRunnable oldRunnable = runnableByUser.get(userId); if(oldRunnable!=null){ oldRunnable.run=false; } SimpleRunnable newRunnableUserOne = new SimpleRunnable(); runnablesByUser.put(userId,newRunnableUserOne); Thread thread = new Thread(newRunnableUserOne); thread.start(); }
The method call will then destroy the old thread, if it is found, release the old one from the scope, replacing it with a new one in ConcurrentHashMap and finally starting a new thread. For instance:
public void startThreeThreads(){ startNewThreadForUser("User1");//starts Thread for User1 startNewThreadForUser("User2");//starts Thread for User2 startNewThreadForUser("User1");//Replaces Thread for User1 }
Running threads are usually managed in the thread pool, and this is rude in many ways, but hopefully it is useful.
I can develop this mechanism if you want.