-1

I have the following code:

class Counter2 extends Thread {

     public Counter2(String s) {
        super(s);
     }; 

     public void run() {
       Thread thread = currentThread();
       for (long count = 0; count <= 1; ++count)
            System.out.println(thread + "COUNT:" + count);
   }
}

public class ThreadTest {

    public static void main(String[] args) {
         Thread secondThread = new Counter2("second");
         Thread thirdThread = new Counter2("third");
         thirdThread.setPriority(8);
         secondThread.start();
         thirdThread.start();
    }
} 

When running the program, I expect to get the following output:

Thread[third,8,main]COUNT:0

Thread[third,8,main]COUNT:1

Thread[second,5,main]COUNT:1

Thread[second,5,main]COUNT:0

Instead I just get different results in different order every time i execute the program and it seems like java is executing the method on both threads at the same time, but i thought it would prioritize the method with the higher priority?

lloiacono
  • 4,714
  • 2
  • 30
  • 46
J.Hurete
  • 31
  • 3

1 Answers1

3

You can't expect any particular output from a threaded program like this unless you explicitly synchronize access to determine the order of operations, and if you do that then the priority doesn't matter at all.

Setting the priority doesn't guarantee a particular order, it merely attempts to prioritize one thread vs. another, but there are so many things that affect the execution of threads that you're unlikely to see what you're hoping for.

If you've ever been in some kind of VIP or priority line and you've noticed the non-VIP people being served faster, well that happens inside computers too.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Exactly, I would check this article for further information about threads: http://www.informit.com/articles/article.aspx?p=26326&seqNum=5 – César Ferreira Mar 13 '18 at 12:34