hellzone
hellzone

Reputation: 5246

How to use multiple cores with java?

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();

Upvotes: 1

Views: 875

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

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

Upvotes: 4

Related Questions