Friday, March 20, 2015

What is Thread?

Thread in java is:
1) an instance of java.lang.Thread
2) a thread of execution – some kind of “lightweight” process which has its own call stack
To initialize the instance of Thread it’s enough to use the default Thread constructor
Thread t = new Thread();
This instruction is useless, because thread does not have any functionality. Another Thread’s constructor which takes an instance of java.lang.Runnable interface allows us to bring some functionality to our thread.

Thread t = new Thread(new Runnable() {

 public void run() {
   System.out.println("Hey from the thread");

Note: as long as any instance of java.lang.Thread implements java.lang.Runnable we can pass any thread instance as a constructor parameter of other thread. To run our thread we need to invoke start 

Then we will see ‘Hey from the thread’ console message. 
Don’t be fooled by Thread’s run() method – it doesn’t launch your thread instructions for asynchronous execution but it in the same thread where this method has been invoked.
There are other Threads frequently used methods such as: sleep [static], yield [static], join. In order to remember what do they all need for it’d be better to take a look on a figure with possible thread states: 

When the thread’s start method is invoked the thread is moving from the new state to runnable
Java Thread Scheduler is responsible for moving thread from Runnable state to Running state. If the Scheduler thinks that your thread and none other thread from the ‘runnable’ pool of thread is valid for execution at the moment of time, then your thread will be executed.
Every started thread eventually comes to its completion
Thread Scheduler may turn the thread back to the Runnable state if some other thread from runnable pool has to be executed. We can move the current thread to the runnable state manually using Thread.yield() method (of course there is no guarantee that it’ll be performed because Thread Scheduler knows better what is going to be executed)
The code above means that the current thread where t.join() is invoked, should suspend its job and wait until thread ‘t’ stops its execution.
Another way of moving current thread to a waiting state is static Thread.sleep() method.
join and sleep methods have a timeout value as its parameters. When the time is expired the thread is moving to the runnable state.

This article doesn’t cover how to stop the thread, but Thread class provides some methods:
Do not use these methods; see more details about its deprecation

No comments:

Post a Comment