Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java multi-threading execution on CPU core

Context

I am new to multi threading and have a question regarding its execution.

Let’s say I have a simple Java multi threading program with

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Runner1 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Runner1: " + i);
        }
    }
}

class Runner2 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Runner2: " + i);
        }
    }
}

public class App {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runner1());
        Thread t2 = new Thread(new Runner2());

        t1.start();
        t2.start();
    }
}

The program is running on a multiple core laptop e.g. 4 cores. My understanding from related post is that multithreading can be executed on a single core.

Question

I was wondering about the behavior of the JAVA 2 threads execution on the cpu.

Will the 2 threads be executed by a single cpu core or will they be allocated to different cpu core for execution? Is there a mechanism or default scenario to decide the allocation?

Thanks!

>Solution :

Each thread has an execution stack that tracks its state. It does not matter whether the two threads run on the same CPU or different CPU. In fact what usually happens is that a thread runs a little bit at a time, and the same CPU can be switch back and forth, running one thread for a while, and running the other for a while.

When the threads are allocated to different CPUs, then the possibility of conflicting updates to shared objects is greater, because the threads could be running at the same time causing fine-grained interweaving of updates to memory. If you design your threads to protect against concurrency problems, then it really does not matter much whether they run on the same CPU or different CPU. It does not matter if the thread is run sometimes on one CPU, and later by a different CPU. The thread holds all its own state and does not matter which CPU runs it.

It seems that Java delegates to the operating system the decision on where to run a particular thread.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading