Strange java concurrency behavior

I have the following code:

class Hi
{
   public static void main (String [] args)
   {
      int a = 1;
      for (int i = 0; i < 50; i++) {
          a = a + i;
          System.out.println ("a before sleep is " + a);
          try {
              Thread.sleep(4000);
          } catch (InterruptedException e) {

          }
          System.out.println ("a after sleep is " + a);
      }
   }
}

I open two console windows and do java Hi in first one. Then wait for about 10 seconds seconds and do the same in the second window. Both outputs are the same:

a before sleep is 1
a after sleep is 1
a before sleep is 2
a after sleep is 2
a before sleep is 4
a after sleep is 4
a before sleep is 7
a after sleep is 7
a before sleep is 11
a after sleep is 11

with no interleaving. So what's the stir about concurrency issues if I even didn't bother to use synchronized statement? Is it because the code run from different console windows is executed on different processor cores? If so, I've carried out this experiment about 20 times and the results are still the same.

Jon Skeet
people
quotationmark

I open two console windows and do java Hi in first one. Then wait for about 10 seconds seconds and do the same in the second window.

You're starting two entirely separate process. That's not using multithreading at all - each process will have its own variables, its own output, everything.

To see multithreading, you need to create threads in a single process. For example:

import java.util.Random;

class Counter implements Runnable {
    private int a;

    public void run() {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            String name = Thread.currentThread().getName();
            a++;
            System.out.println(name + " Before sleep, a = " + a);
            try {
                // Add a little more uncertainty...
                Thread.sleep(random.nextInt(1000));
            } catch (InterruptedException e) {
                // Ignored
            }
            System.out.println(name + " After sleep, a = " + a);
        }
    }
}

public class ThreadingTest {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(counter);
        Thread t2 = new Thread(counter);
        t1.start();
        t2.start();
    }
}

people

See more on this question at Stackoverflow