Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.1 kB
3
Indexable
Never
class A {
    private int value;

    public A(int initialValue) {
        this.value = initialValue;
    }

    public void increment() {
        value++;
    }

    public void decrement() {
        value--;
    }

    public int getValue() {
        return value;
    }

    public static void main(String[] args) {
        A resource = new A(0);

        Thread incrementThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.increment();
                System.out.println("Incremented: " + resource.getValue());
            }
        });

        Thread decrementThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.decrement();
                System.out.println("Decremented: " + resource.getValue());
            }
        });

        incrementThread.start();
        decrementThread.start();

        try {
            incrementThread.join();
            decrementThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final value: " + resource.getValue());
    }
}