1

Assume I have the following fragment of code:

Thread x = new Thread() {

        public void run() {

            while (true) {
                // do something
            }
        }

    };

    Thread y = new Thread() {

        public void run() {

            while (true) {
                // do something
            }
        }

    };

 x.start();
 y.start();

Now my question is since these two threads both run infinite loops, will they both start running at the same time?

ninesalt
  • 4,054
  • 5
  • 35
  • 75

3 Answers3

3

Well it depends JVM thread scheduler,type of machine you are running your code (single core or multicore) and OS, When you first-time call start() method on a new thread it just moves from new to Runnable state.

The thread scheduler which is the part of the JVM decides which thread should run at any given moment, and also takes threads out of the run state.Any thread in the runnable state can be chosen by the scheduler.

Sumit Rathi
  • 693
  • 8
  • 15
0

The same code might generate different output when you execute it on the same or different systems, at different times. The exact time of thread execution is determined by how the underlying thread scheduler schedules the execution of threads. Because thread scheduling is specific to a specific JVM and depends on a lot of parameters, the same system might change the order of processing of your threads.

Dogrock
  • 1
  • 2
0

If your computer has a single core : Only one thread will run at a time. Hence one will start before the other

If your computer has multiple cores : The two threads could run simultaneously(one thread on each core). Hence they could start at the same time but there is no guarantee

In either case, it won't depend upon whether the thread is running an infinite loop or not.

abhaybhatia
  • 599
  • 1
  • 7
  • 16