Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a.run() and a.start()

 
vini singh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class TestThread extends Thread
{
private int i;
public void run()
{i++;
}
public static void main(String []s)
{
TestThread a=new TestThread();
a.run();
System.out.println(a.i);
a.start();
System.out.println(a.i);
}
}


How can be the output 11 0r 12 ?and what is meant by new call stack and how is thread behaving?
 
Angel Taveras
Ranch Hand
Posts: 84
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vini,

Every java program start with the main method, this it's the main thread. Each Thread has a call stack. In java the lifecycle of a thread begins when
you call the start method. Like any other class you can call all the methods of Thread object but they will run in the same thread (even if you call the run method).

Regarding the other question how can be the output 1 1 or 1 2?

Scenario a: (Single Threaded App)

The TestThread class gets instantiated in the main thread the call to run will increment the value of i to 1, and if you call run again from the same thread will increment it again, but that you already now this .

Scenario b: (Multithreaded app, your example)

The TestThread class gets instanciated in the main thread. Then the call to run it's made and the value of i it's incremented by 1. Everything is fine. The things starts to change when you call the start method on the TestThread class it will create a new Thread of execution and your program now have two threads the main thread and the Thread-0 (this it's the newly created thread). The two threads could read simultaneously reading the i variable and from now on you don't know if the vm will grant the privilege of execution to the Thread-0 or it will continue executing the main thread. If the vm determinate that the main thread will go on, then 1 1 will be printed. If the vm determinate that the Thread-0 will run then the i variable it's incremented by 1 and now it's value it's 2, and after the execution of Thread-0 then 1 2 will be printed.

I recommend that you read this article and this one too. These have a very basic definition of what things could happens when threads are involved, and any documentation related to threads in java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic