I'm learning Threads in Java and I though of creating a simple stack to test Thread synchronization. Here is the stack class:
public class Stack {
private int counter;
private String[] storage;
public Stack(final int number) {
storage = new String[number];
counter = 0;
}
public synchronized void push(final String msg) {
if(counter == storage.length) {
System.out.println("Counter full");
} else {
storage[counter++] = msg;
}
}
public synchronized String pop() {
if(isEmpty()) {
System.out.println("There is nothing to pop");
return null;
} else {
String lastElement = storage[--counter];
storage[counter] = null;
return lastElement;
}
}
public boolean isEmpty() {
return counter == 0 ? true : false;
}
public synchronized void printElements() {
for(int i=0; i < storage.length; i++) {
System.out.println(storage[i]);
}
System.out.println("Number of elements "+counter);
}
}
And here is the main method:
public static void main(String[] args) {
Stack s = new Stack(10);
final Thread t1 = new Thread(() -> {
for(int i=0; i < 2; i++) {
s.push("Hello "+i);
}
for(int i=0; i < 2; i++) {
s.push("How are you? "+i);
}
});
final Thread t2 = new Thread(() -> {
for(int i=0; i < 2; i++) {
s.push("Nice to meet you "+i);
}
s.pop();
});
t1.start();
t2.start();
try {
t2.join();
t1.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
s.printElements();
}
Using the synchronized word is basic way of making a method gets executed by one Thread at a time only. Most of the time, I receive the sequence
Hello 0
Hello 1
How are you? 0
How are you? 1
Nice to meet you 0
null
null
null
null
null
Number of elements 5
which is the desired result. However there are also some situations where different sequence is returned and this is where my question appeared. Using synchronized will guarantee that only one thread at a time came execute a method i.e. securing the critical section. But it doesn't mean that the sequence of operations, specified in the lambda expression for creating a Runnable, will be executed always in the same flow, or?
(Sorry, if it's a dummy question)