• Post Reply Bookmark Topic Watch Topic
  • New Topic

Priority of Main Thread  RSS feed

 
Lalit Kapoor
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code:
class A implements Runnable{
public void run(){
i+=1;
System.out.println("inside run");
}
void printi(){System.out.println("i="+i);}
volatile int i = 1;
}

public class Test{
public static void main(String[] args){// throws Exception{
A a= new A();
a.printi();
Thread t = new Thread(a);
t.start();
a.i +=1;
//Thread.sleep(1000);
a.printi();
}
}
This code compiles well and gives the output:
i = 1
i = 2
inside run
But the following code:
class A implements Runnable{
public void run(){
i+=1;
System.out.println("inside run");
}
void printi(){System.out.println("i="+i);}
volatile int i = 1;
}

public class Test{
public static void main(String[] args) throws Exception{
A a= new A();
a.printi();
Thread t = new Thread(a);
t.start();
a.i +=1;
Thread.sleep(1000);
a.printi();
}
}
The output is:
i = 1
inside run
i = 3

Does the main thread has higher priority then the other threads it originates?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All threads have the same (default) priority when they are created.

Thread.start() takes a comparatively long time to invoke run(). Without the sleep(), main() completes before run() is even called. This has nothing to do with priority -- it just shows that starting a thread is an expensive operation.
[ June 21, 2004: Message edited by: Ernest Friedman-Hill ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!