Confusion regarding Threads in Java

Because the threads use a single variable to count.

A x+=1 (1)
B x+=1 (2)
A starts print (2), and goes to sleep
B prints 2
B keeps working, incrementing x, printing 3 to 11
B goes to sleep
A finishes the print of "2" it started a while back 

Clarification of followup questions:

x is owned by the object ob of class abs there is only one which is shared across threads.

i is owned by the function public void increment() and there are two independent calls of it.

As to the behaviour of sleeping on printing… That’s pretty much the whole point of threads. print takes forever from a cpu point of view and there are exclusive assets (there is only one console) involved

Leave a Comment