0

I am getting reacquainted with Java. I am doing multi threading and testing the priority logic. I have a main class and another class that implements runnable,

public class Threading {

  public static void main(String[] args) {

        System.out.println("Main priority is: " + Thread.currentThread().getPriority());
        MyRunnable myRunnable = new MyRunnable();
        Thread thread1 = new Thread(myRunnable);
        thread1.setPriority(10);
        thread1.setName("MyRunnable");
        thread1.start();

        for (int i = 0; i < 5; i++) {
            System.out.println("Main Thread !!");
        }

    }
}

The class that implements Runnable is below,

class MyRunnable implements Runnable {
@Override
public void run() {
    System.out.println("Executing Thread name is: " + Thread.currentThread().getName());
    for (int i = 0; i < 5; i++) {
        System.out.println("Implements Runnable !!");
    }
}
}

If my understanding is correct the loop in the MyRunnable class should be completed first followed by the one in the main method as i have set a higher priority of 10 for the MyRunnable class. But i am getting mixed outputs however i.e. sometime Main Thread is printed followed by the Implements Runnable. I understood the processor or the O.S one is working on could have an impact on the output. I appreciate your input.

Ayubx
  • 597
  • 2
  • 9
  • 19
  • 2
    What your are seeing is to be expected. Why would you think the loop in the MyRunnable class would finish first. You have started it on a different thread. Therefor they run concurrently, Essentially having a nondeterministic race to the finish. – bhspencer Mar 12 '16 at 18:12
  • @bhspencer I have set a higher priority of 10 for the MyRunnable class and that's why I am expecting that. Is there a way to get the code in the MyRunnable class to be executed first by implementing the thread logic ? – Ayubx Mar 12 '16 at 18:19
  • 1
    Thank you @luketorjussen. I think that will be useful. – Ayubx Mar 12 '16 at 18:24

0 Answers0