-
Notifications
You must be signed in to change notification settings - Fork 0
Synchronisation: Using the class instance as monitor object
Devrath edited this page Feb 14, 2024
Β·
1 revision
- Observe that Since we have synchronized the increment and decrement functions the result of the counter is always 0 no matter how many times we execute the program.
- This is because the increment and decrement are executed by two different threads in parallel but increment and decrement happen 3 times and the result should be 0 since we have synchronized.
<---------------Start of execution--------------->
Incremented 1 by {Thread-0}
Decremented 0 by {Thread-1}
Incremented 1 by {Thread-0}
Decremented 0 by {Thread-1}
Decremented -1 by {Thread-1}
Incremented 0 by {Thread-0}
Result of the counter:-> 0
<---------------End of execution----------------->
fun main(args: Array<String>) {
println("<---------------Start of execution--------------->")
println()
val sharedResource = SharedResource()
// Create a thread-1
val runnable1 = Runnable {
for (i in 1..3){
sharedResource.increment()
Thread.sleep(20)
}
}
// Create a thread-2
val runnable2 = Runnable {
for(i in 1..3){
sharedResource.decrement()
Thread.sleep(20)
}
}
val thread1 = Thread(runnable1)
val thread2 = Thread(runnable2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
println()
println("Result of the counter:-> ${sharedResource.getResult()}")
println()
println("<---------------End of execution----------------->")
}
class SharedResource {
private var counter = 0
@Synchronized
fun increment(){
counter++
println("Incremented $counter by {${Thread.currentThread().name}}")
}
@Synchronized
fun decrement(){
counter--
println("Decremented $counter by {${Thread.currentThread().name}}")
}
@Synchronized
fun getResult(): Int {
return counter
}
}