How to stop 2 threads in java, my req would be you create 2 threads and running them, but after one minute you need to stop one thread and after 2 minutes you need to stop second thread. Can anyone let me know how to do this by using only one variable.
-
Hi Ramya, Can you show what you have tried (code sample) and what you are trying to achieve? Take a look at our short guide on asking good questions: stackoverflow.com/help/how-to-ask – dubes Mar 08 '16 at 07:39
-
Any posted answer so far omits to wait for the finished threads. Just because a thread has been signaled to finished, does not mean it finishes "immediately". – Markus Kull Mar 08 '16 at 08:09
3 Answers
Something like this might work
t1.start();
t2.start();
new Thread(){
public void run(){
Thread.sleep(1000*60);
t1.interrupt();
Thread.sleep(1000*60);
t2.interrupt();
}
}.start();
You are basically creating a new thread to trigger interrupts after 1 minute and 2 minutes respectively. Now all you need to do is catch the interrupt in your threads and return from them.
You can do something like this to detect an interrupt inside your 2 threads.
public void run()
{
try
{
while (!interrupted() && more work to do)
{
//do more work
}
}
catch(InterruptedException exception)
{
// thread was interrupted during sleep or wait
}
finally
{
//cleanup, if required
}
// exit run method and terminate thread
}

- 927
- 1
- 11
- 37
-
-
Hi @fsociety, is there possible that we can use the above logic inside main thread and check for the time and call t1.interrupt and t2.interrupt. Thanks for your helpful answer. – Ramya B Mar 08 '16 at 19:59
-
@Ramya B the first code segment can go inside your main thread. Basically the main thread will create 3 threads; your two threads and one thread to trigger the interrupts. Up-vote the answer if you've found it helpful :) – Priyath Gregory Mar 09 '16 at 04:51
-
i upvoted yours, but it will be only publicly displayed once i reaches 15 points...:) – Ramya B Mar 14 '16 at 08:02
Use a volatile or final long variable that you load before start with the current time in milliseconds
volatile long startTime = System.currentTimeMillis();
In your threads run
method check the condition
public void run(){
while (System.currentTimeMillis()-startTime < threadRun){
//...do something
//or simulate work by Thread.sleep()
}
//The thread will shutdown when it exits the while loop
}
With threadRun = 60*1000
and threadRun = 2 * 60 * 1000
for first, respectively second thread.
A side note it is not safe to compare the results of System.nanoTime()
calls between different Threads. Even if the events of the Threads happen in a predictable order, the difference in nanoseconds can be positive or negative, while System.currentTimeMillis()
is safe for use between threads.

- 1
- 1

- 3,462
- 5
- 24
- 43
-
-
`long`-currentTimeMillis instead of `int` please. `volatile` could also be replaced by `final` here because of no changes. `nanoTime()` is monotone (as is `currentTimeMillis()`), so it can be used to measure or test a duration. The only quirk of `nanoTime()`: It is an independent clock, so it can only be used to measure durations, but not to get absolute time. – Markus Kull Mar 08 '16 at 07:51
-
@MarkusKull I agree completely with your first two corrections, however even if using one variable (`startTime`) initialized and checked with `nanoTime()` can be used here (since the drift is less than millisecs ), it is not thread safe (that is why it is a side note) – Radu Ionescu Mar 08 '16 at 08:02
-
Hi @RaduIonescu, but with the while loop, you have to do the same thing over and over until it finishes, i just want to stop the current thread to stop after a minute and the second one to stop after 2 minutes. – Ramya B Mar 08 '16 at 21:00
-
@RamyaB you can add `Thread.sleep(x)`, to sleep `x` ms, but this means you accept an error of at least `x` ms (the thread can sleep just before 1 minute and will not "wake up" to check until `x` ms into the future ). Also ? `Thread.sleep`, does not guarantee precision. It does it by best effort. – Radu Ionescu Mar 08 '16 at 21:10
Well this depends on what your thread is exactly doing. If the thread executes an endless loop, I guess you could use a flag, to detect if the loop should be stopped.
public class MyRunnable implements Runnable {
ScheduledExecutorService scheduledStop = Executors.newScheduledThreadPool(1);
boolean isRunning;
int stopDelay;
public MyRunnable(int duration) {
stopDelay = duration;
}
@Override
public void run() {
scheduledStop.schedule(new Runnable() {
@Override
public void run() {
isRunning = false;
}
}, stopDelay, TimeUnit.MINUTES);
while (isRunning) {
//do something
}
}
}

- 4,977
- 5
- 34
- 62