I have decided to face this monster called concurrency and broaden my threading knowledge, so before I read through Joshua Bloch’s book, I decided to code something random to help me understand the problem I might face before reading the book, hopefully I can then come to my code and make corrections but then I landed into this pit and I am hoping someone can explain.
I have the following:
public class Arithmetic implements Runnable {
int number;
public Arithmetic(int x){
this.number = number + x;
}
@Override
public void run() {
Thread.currentThread().setName("thread-"+number +" > " + "number = "+getNumber());
System.out.println(Thread.currentThread().getName());
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = getNumber() + number;
}
}
Then a main class:
public class Main {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
for (int x=0; x<=5; x++){
Thread thread = new Thread(new Arithmetic(x));
thread.start();
}
}
}
With this I get the following as output:
run:
main
thread-0 > number = 0
thread-1 > number = 1
thread-2 > number = 2
thread-3 > number = 3
thread-5 > number = 5
thread-4 > number = 4
Notice: The 5 comes before 4
But then I change my main class to:
public class Main {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
for (int x=0; x<=5; x++){
Runnable runnable = new Arithmetic(x);
runnable.run();
}
}
}
I get the output below:
run:
main
thread-0 > number = 0
thread-1 > number = 1
thread-2 > number = 2
thread-3 > number = 3
thread-4 > number = 4
thread-5 > number = 5
Notice: Correct sequence
I was hoping both main(s) will produce erratic result(Like Thread implementation), then I would then use some thread safety measures like synchronised access etc. but why does the Runnable call act as if Arithmetic is thread safe?
IMO, the difference between extending Thread class and implementing Runnable is for decoupling purposes. Apologies if this is a duplicate question, I can’t seem to find an answer.
Thanks in advance.
Runnablesdo not start new threads it is simply and interface, so this means your second piece of code runs synchronously.Threadsare new threads so you they can run in parallel, which is why the output comes out of order – the 4th thread executes slower than the 5th.