user3111311
user3111311

Reputation: 8001

Why do my Java threads seem to run on one core only, when my machine has two?

Why do my Java threads seem to run on one core only, when my machine has two?

My program has 10 threads and each prints more things. In the output I can see that the printing is in such order that, once a thread begins it finishes, and only then another thread starts printing. So, there is none of the interleaved print statements I expected to see from different threads.

public class Calculator implements Runnable {

        private int number;

        public Calculator(int number) {
            this.number=number;
        }

        @Override
        public void run() {
            for (int i=1; i<=10; i++){
                    System.out.printf("%s: %d * %d = 
                    %d\n",Thread.currentThread().getName(),number,i,i*number);
            }
        }

}

public class Main {

    public static void main(String[] args) {
            for (int i=1; i<=10; i++){
                    Calculator calculator=new Calculator(i);
                    Thread thread=new Thread(calculator);
                    thread.start();
            }
    }
}

Best Regards

Upvotes: 0

Views: 82

Answers (1)

Marco13
Marco13

Reputation: 54639

To shorten the discussion in the comments, and as a simple illustration, you may try this modified version of your Calclulator. It should print the output in a nicely mixed fashion.

class Calculator implements Runnable
{
    private int number;

    public Calculator(int number)
    {
        this.number = number;
    }

    @Override
    public void run()
    {
        for (int i = 1; i <= 10; i++)
        {
            System.out.printf("%s: %d * %d = %d\n", 
                Thread.currentThread().getName(), 
                number, i, i * number);
            someRandomDelay();
        }
    }

    private static void someRandomDelay()
    {
        int ms = (int) (100 + Math.random() * 200);
        try
        {
            Thread.sleep(ms);
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
        }
    }

}

Upvotes: 2

Related Questions