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?

4
  • I think you should revisit the definition of Thread. Mar 27, 2016 at 17:50
  • Never assume anything about the timing of threads.
    – Natecat
    Mar 27, 2016 at 17:57
  • You are never even starting another thread since you are calling the run() method on the threads instead of start(). Currently you will begin an infinite loop in x.run() on the main thread. Mar 27, 2016 at 17:58
  • @georgemulligan Yeah, I meant start(). My bad.
    – ninesalt
    Mar 27, 2016 at 18:02

3 Answers 3

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.

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.

1
  • So what can I do to ensure they both right at the same time?
    – ninesalt
    Mar 27, 2016 at 18:23
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.