K
K
Karina2015-03-24 22:18:11
Java
Karina, 2015-03-24 22:18:11

How to stop execution of threads?

Whenever I call a function
addMessage()
I create new thread's. In these threads, I just do:
Thread.sleep(5000);
What I want to do: I need to wait for this thread to wake up and run a certain method (deleteMessage() ) ONLY once. And it turns out for me that how many times I call the addMessage function, so many times I call deleteMessage (). I've tried interrupt() threads, I've tried join(). I don't get anything.
How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
igorcc, 2015-03-24
@iKapex

Good evening. Everything is detailed here.
docs.oracle.com/javase/1.5.0/docs/guide/misc/threa...

A
Alexander Rulev, 2015-03-24
@Rulexec

Usually do not kill threads from the outside, because this can lead to undefined consequences.
To do something once from many threads, you can use, for example, atomic booleans.
We create an instance of AtomicBoolean , to which all these threads have a reference, which will initially be false .
Then we do CAS:

// AtomicBoolean isDeleted;
if (isDeleted.compareAndSet(false, true)) {
    deleteMessage();
}

compareAndSet takes the expected value and if it really is, changes the flag to what we want and returns true if we guessed it, otherwise false. And this is done atomically. Those. only one thread will change the variable and get true and call deleteMessage.
But in general, it seems unlikely that you really need to create threads for this task. Perhaps you just need a variable, they say, “is there a timer that will call deleteMessage now”, as well as a Timer that will call deleteMessage after some time. You can cancel it, if that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question