Thread, The real worker
November 16, 2017
Reading
Add Comment
what is thread in java
A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is a the java.lang.Thread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.But for better understanding the threads, we are explaining it in the 5 states.The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
- New
- Runnable
- Running
- Non-Runnable (Blocked)
- Terminated
An application that creates an instance of
Thread
must provide the code that will run in that thread. There are two ways to do this:- Provide a
Runnable
object. TheRunnable
interface defines a single method,run
, meant to contain the code executed in the thread. TheRunnable
object is passed to theThread
constructor, as in theHelloRunnable
example:
- public class HelloRunnable implements Runnable {
- public void run() {
- System.out.println("Hello from a thread!");
- }
- public static void main(String args[]) {
- (new Thread(new HelloRunnable())).start();
- }
- }
- Subclass
Thread
. TheThread
class itself implementsRunnable
, though itsrun
method does nothing. An application can subclassThread
, providing its own implementation ofrun
, as in theHelloThread
example:
- public class HelloThread extends Thread {
- public void run() {
- System.out.println("Hello from a thread!");
- }
- public static void main(String args[]) {
- (new HelloThread()).start();
- }
- }
Notice that both examples invoke
Thread.start
in order to start the new thread.
Which of these idioms should you use? The first idiom, which employs a
Runnable
object, is more general, because the Runnable
object can subclass a class other than Thread
. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread
. This lesson focuses on the first approach, which separates the Runnable
task from the Thread
object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.
The
Thread
class defines a number of methods useful for thread management. These include static
methods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and Thread
object.
Check here the gist behind thread.
0 comments:
Post a Comment