0

Lets say I have code like this:


class A extends Thread {
    Thread t = new Thread();
    private static int id = 0;

    A(){
        id++;
        this.t.start();
    }

    private synchronized static int getId() { return id; }

    public void run() { System.out.println(getId()); }
}

public class Test throws InterruptedException {
    public static void main(String[] args) {
        A thread1 = new A();
        A thread2 = new A();
        try {
            thread1.t.join();
            thread2.t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main thread ends here");
    }
}

I'm expecting the output like this:


1
2

But the output is:


2
2

What should I do here? Thanks for help. Q.

1 Answers1

2

For this case, you should use AtomicInteger instead of int, and change methods.

public class Test
{

    public static void main(String[] args) throws InterruptedException
    {
        final A thread1 = new A();
        final A thread2 = new A();
        try
        {
            thread1.join();
            thread2.join();
        }
        catch (final InterruptedException e)
        {
            e.printStackTrace();
        }
        Thread.sleep(1000);
        System.out.println("Main thread ends here");
    }

    public static class A extends Thread
    {
        private static final AtomicInteger id = new AtomicInteger(0);

        A()
        {
            start();
        }

        private synchronized int getID()
        {
            return id.get();
        }

        @Override
        public synchronized void run()
        {
            id.incrementAndGet();
            System.out.println(getID());
        }
    }
}
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
  • Unless you fix the messed up thread situation this does not really change anything. The original output will always be `12` anyway, since the increment happens synchronously in the ctor. (well, the original output *would* be that, right now there is no output since `run` is never executed) – luk2302 Dec 10 '18 at 13:16
  • 1
    Read the code more carefully - `id` is only ever mutated by the main thread. The code does not do anything remotely sensible - adding `AtomicInteger` won't fix the nonsense the OP has written. – Boris the Spider Dec 10 '18 at 13:16
  • I fixed answer to print correct numbers – Slava Vedenin Dec 10 '18 at 13:37
  • @luk2302 I corrected OP class and I can post the answer if you open the question – Mohsen Dec 10 '18 at 13:37
  • 1
    @Spara you are out of lock, OP already agreed that the question was duplicate - the real problem he wanted to solve was that of an atomic increment, which the duplicate answers. – luk2302 Dec 10 '18 at 16:18