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() {

 @Override
 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 
method:

t.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: 



           
1
NEW -> RUNNABLE
When the thread’s start method is invoked the thread is moving from the new state to runnable
2
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.
3
Every started thread eventually comes to its completion
4
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)
5
t.start();
t.join();
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.
6
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:
                t.destroy();
                t.stop();
                t.suspend();
Do not use these methods; see more details about its deprecation http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

No comments:

Post a Comment