I have a program where I want my threads to make a sort of update to something else, but since I start all of the threads at the same time, they make the update at the same time which defeats the purpose because they all overwrite each other. I want a thread to update something, have that something use it quickly, then get changed afterwards. Is there a way to allow any thread to go first and then have the others wait? It feels like I can't do anything because if I change the thread class, then all of the threads will perform the change and still execute at the same time. I am using a GUI too, so I can't just use Thread.Sleep between each thread's start call. I don't think any code would help the question, I just want to know if there's a way to block all threads but one, or delay each thread from getting to the same line of code at the same time, since they all change a variable.
Asked
Active
Viewed 404 times
-2
-
Just start a new thread at the end of another thread. Also read `RxJava` that helps you manage threading tasks effectively. – TaQuangTu Oct 09 '20 at 04:07
-
2Here is a quote from [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _Include just enough code to allow others to reproduce the problem._ – Abra Oct 09 '20 at 04:11
-
1Please check about `synchronized` block/method. That will help with code block/method which shouldn't be executed by multiple threads in parallel. – Viral Lalakia Oct 09 '20 at 04:13
1 Answers
0
Use a synchronized block for this purpose. When a block of code is wrapped in synchronized, only a single thread can access it, and other threads wait for their turns
synchronized(this)
{
// your line of code
}

Rajkumar Gaur
- 95
- 6