Не могу понять, почему данный код не работает корректно.
import java.util.concurrent.atomic.AtomicInteger;
public class Test1 extends Thread {
public static AtomicInteger counter = new AtomicInteger(0);
synchronized void doWork1() {
counter.incrementAndGet();
counter.incrementAndGet();
System.out.println("Thread+++" + " - " + Test1.counter);
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
}
}
synchronized void doWork2() {
counter.decrementAndGet();
counter.decrementAndGet();
System.out.println("Thread---" + " - " + Test1.counter);
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
}
}
public void run() {
for (int i = 0; i < 100; i++) {
doWork1();
doWork2();
}
}
public static void main(String[] args) {
Test1 test1 = new Test1();
test1.start();
Test1 test2 = new Test1();
test2.start();
}
}