Answer the question
In order to leave comments, you need to log in
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
Good evening. Everything is detailed here.
docs.oracle.com/javase/1.5.0/docs/guide/misc/threa...
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();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question