In the course of training, as well as with the analysis of multithreading, I decided to try my hand at thread synchronization. In this regard, I made a small test, where the creation of threads occurs through the creation of objects. And I got into a problem situation, the streams cannot be synchronized, and I don't understand what the problem is.
public class MainClass {
static int firstInt;
static int secondInt;
static int thirdInt;
public static void main(String[] args) {
SecondClass s1 = new SecondClass("Первый");
SecondClass s2 = new SecondClass("Второй");
SecondClass s3 = new SecondClass("Третий");
SecondClass s4 = new SecondClass("Четвертый");
SecondClass s5 = new SecondClass("Пятый");
try {
s1.t.join();
s2.t.join();
s3.t.join();
s4.t.join();
s5.t.join();
} catch (InterruptedException exp) {
System.out.println("Прервано!");
}
System.out.println(firstInt);
System.out.println(secondInt);
System.out.println(thirdInt);
}
}
class SecondClass implements Runnable {
String name;
Thread t;
SecondClass(String a) {
name = a;
t = new Thread(this);
t.setName(name);
t.start();
System.out.println("Поток с именем "+t.getName()+" создан и запущен.");
}
private void plusFirstInt() {
MainClass.firstInt++;
}
private void plusSecondInt() {
MainClass.secondInt++;
}
private void plusThirdInt() {
MainClass.thirdInt++;
}
private synchronized void fori() {
try {
for (int i = 0; i < 10000; i++) {
plusFirstInt();
plusSecondInt();
plusThirdInt();
}
Thread.sleep(10);
} catch (InterruptedException exp) {
System.out.println("Прервано!");
}
}
@Override
public void run() {
fori();
}
}
Tried to sync using object reference.
Object a = new Object();
private void plusFirstInt() {
synchronized (a){
MainClass.firstInt++;
}
}