What is the difference between the first and second codes? Why, seeing the first one, the outputs come out messy or repeated and in the second they turn out well? In the first, the syncronized method is that of 'Person', and having the same instance for the two threads, I do not understand why the outputs go wrong or repeated.
public class Main {
public static void main(String[] args) {
BolsaPersonas bolsa = new BolsaPersonas();
Thread thread = new Thread(bolsa);
Thread thread2 = new Thread(bolsa);
thread.start();
thread2.start();
}
}
class BolsaPersonas implements Runnable {
Persona persona = new Persona();
@Override
public void run() {
incrementar();
}
public synchronized void incrementar() {
for (int i=0;i<5000;i++) {
persona.doStuff();
}
}
}
class Persona {
private int id = 1;
private Object objeto = new Object();
public void doStuff() {
System.out.println("Thread: " + Thread.currentThread().getName() + ". ID: " + id);
id++;
}
}
class BolsaPersonas implements Runnable {
@Override
public void run() {
Persona persona = new Persona();
for (int i=0;i<5000;i++) {
persona.doStuff();
}
}
}
class Persona {
private int id = 1;
private Object objeto = new Object();
public synchronized void doStuff() {
System.out.println("Thread: " + Thread.currentThread().getName() + ". ID: " + id);
id++;
}
}