Just messing around with multithreading to learn more about it with regards to the synchronized
keyword and other aspects I wrote a simple class and a main class to call methods of that class in different threads. I saw what I was expecting a few times (values changing by 2 instead of just 1) but then came across a larger jump which I can't understand - does anyone know how it happened?
Here's my code:
public class SeatCounter {
private int count = 0;
public int getSeatCount() {
return count;
}
public void bookSeat() {
count++;
}
public void unBookSeat() {
count--;
}
}
and
public class Main {
public static void main(String args[]) {
final SeatCounter c = new SeatCounter();
Thread t1 = new Thread() {
public void run() {
while(true) {
c.bookSeat();
System.out.println(c.getSeatCount());
}
}
};
Thread t2 = new Thread() {
public void run() {
while(true) {
c.unBookSeat();
System.out.println(c.getSeatCount());
}
}
};
t1.start();
t2.start();
}
}
and I got this at some point in my console:
-16066
-16067
-16068
-16069
-16031
-16069
-16068
-16067
-16066
EDIT: Thanks for the swift replies, I know about using synchronized, I was just playing around to see what went wrong, the thing I don't understand is how it changed by a jump of so much (-16069 to -16031) in one jump, since a printout statement should happen with every change of the stored value and with 2 threads running without synchronization I would've assumed that would mean at most a jump of 2 in the value.