1

As we all know, i++ is not atomic in java, so I try to write a program to prove that.

My idea is to new several threads and inside each thread, increase count(which is a static field in the Main class).

If

  threadNum * iteration > count, 

then we can prove i++ is not atomic, but actually I've always got them equal.

Here is my code:

import java.util.ArrayList;
import java.util.List;

public class  ConcurrentTest{
    private static int count = 0;

    public static void main(String[] args) throws Exception{
        List<Thread> threads = new ArrayList<>();
        for(int i = 0; i<12; ++i){
            threads.add(new Thread(() -> {
               for(int j=0; j<1000000; ++j) {
                   count++;
               }
            }));
        }
        for(Thread t: threads){
            t.start();
            t.join();
        }
        System.out.println(count);
    }
}

The result is 12000000.

And no mater how I change i and j in the above program, i*j === count.

I don't know if this is helpful: this program has been tested on JRE 6, 7 and 8. I haven't tested it in Java 5 or earlier.

JeremyJi
  • 101
  • 1
  • 8

2 Answers2

5

The join method makes the currently executing thread wait for the completion of the thread upon which it is called. In your code, you start a thread, then wait for it to complete, then start another.

Change

for(Thread t: threads){
        t.start();
        t.join();
}

to

for(Thread t: threads){
        t.start();
 }

for(Thread t: threads){
        t.join();
}

This will start all your threads running, and then wait for them all to complete.

Colin
  • 3,394
  • 1
  • 21
  • 29
0

Change

for(Thread t: threads){
            t.start();
            t.join();
        }

In

for(Thread t: threads){
            t.start();
        }
for(Thread t: threads){
            t.join();
        }

This way it Will run multithreaded, while in your way one thread at time is executed.

Tu.Ma.
  • 1,325
  • 10
  • 27