1

I am trying to understand how java threads works with CPU cores. I have a 4 core CPU and when I try to run below codes execution times are interesting. Why it doesn't speed up with multiple threads? Am I doing something wrong?

availableProcessors() returns 4 by the way.

Below code takes nearly 27 seconds;

        Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int x = 0;
            while(x < 10000000){
                System.out.println(x);
                x++;
            }
        }
    };

    Thread t1 = new Thread(runnable);

    t1.start();

When I use multiple threads it takes 33 seconds;

Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int x = 0;
            while(x < 5000000){
                System.out.println(x);
                x++;
            }
        }
    };

    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            int x = 5000000;
            while(x < 10000000){
                System.out.println(x);
                x++;
            }
        }
    };

    Thread t1 = new Thread(runnable);

    t1.start();


    Thread t2 = new Thread(runnable2);

    t2.start();
hellzone
  • 5,393
  • 25
  • 82
  • 148
  • Possible duplicate of [How does Java make use of multiple cores](http://stackoverflow.com/questions/4436422/how-does-java-makes-use-of-multiple-cores) – OneCricketeer May 04 '16 at 18:59

1 Answers1

4

Your program has a sequential bottleneck which is printing to the terminal.

System.out.println has a synchronized block in it and hence writes are one at a time, and hence your code is not parallel.

Sequential parts (including coordination) of the program is what governs its performance according to Amdahl's law

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77