Reputation:
I've been studying java multi-thread on the last weeks. I learned about synchronized, and understood that synchronized avoid various threads access the same propertie at same time. I wrote this code to run two threads at the same thread.
val gate = CyclicBarrier(3)
val obj = SynchronizedCounter()
var nah = object : Thread() {
override fun run() {
gate.await()
obj.increment()
}
}
var blah = object : Thread() {
override fun run() {
gate.await()
println(obj.value())
}
}
nah.start()
blah.start()
gate.await()
class SynchronizedCounter {
private var c = 0
@Synchronized
fun increment() {
c++
}
@Synchronized
fun decrement() {
c--
}
@Synchronized
fun value(): Int {
return c
}
}
Output: 0 Wouldn't return 1? Because the second thread is run after the one
Upvotes: 1
Views: 7815
Reputation: 10605
Both nah
and blah
set up jobs to be run on a different thread than their own. So when they each call start
, they are just flagging the thread scheduler to start them. start
returns immediately and the current thread continues running the main line of code until something happens to make it defer. At that point, the scheduler does it's thing, running anything that is ready and waiting to run. You should not expect a particular order, nor should you try to predict an order. That is why you have synchronization constructs to use in your code.
You could run your tasks on a single threaded Executor like in this SO answer (for java though, you would have to adapt).
Upvotes: 2