Wednesday 21 August 2019

Thread in java | java thread Tutorial | Creating a thread in java - Online Help

Thread in java:

Java's multithreading system is built upon the thread class, its method and its companion interface Runnable. Thread is a sequential flow of control. A thread is a sequence of execution within a program. Since you can't directly refer to the real state of a running thread, you will deal with it through its proxy.

To create a new thread, your program with either extends Thread or implement the Runnable interface.

The thread class defines several methods that help manage threads. The following table lists the various thread methods:

                               Methods
                               Meaning
start()
Starts a thread by calling its run method.
run()
The entry point of a thread i.e. defines while the thread is running
sleep()
Suspends a thread for a period of time.
join()
Waits for a thread to terminate.
isAlive()
Determines if a thread still running.
getName()
Gets the name of the thread.
getPriority()
Returns the priority of a thread.
Yield()
Current thread to yield control of the process to the thread.

Main thread:

When a java program starts up, one thread begins running immediately. This is usually called the main thread of your program because it is the one that is executed when your program begins. The main thread is important for two reasons:

  • It is the thread from which other child thread will be swapped
  • It must be the last thread to finish execution. When the main thread stops, your program terminates.

      Although the main thread is created automatically when your program is started, it can be controlled through a thread object. To do so, you must obtain a reference to it by calling the method currentThread(), which is a public static member of thread. Its general form is,

static Thread currentThread()

    This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control its just like any other thread.

Sample program:
//controlling the main thread.

class currentlythreaddemo
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("current thread:"+t);

//change the name of the thread

t.setNmae("my thread");
System.out.println("After name change:"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("main thread interrupted");
}
}
}

Output:
current thread:Thread(main,5,main)
After name change: Thread(my thread,5, main)
5
4
3
2
1

Also Read:
Separator in java



Creating a thread in java:

The thread class in the java.lang package allows to create and manages thread. In the most general sense, you create a thread by instantiating an object of the type Thread.Java defines two ways to creating the thread.
  • you can extend a thread class.
  • you can implement the runnable interface.


Implementing Runnable:

The easiest way to create a thread is to create a class that implements the runnable interface. Runnable interface abstract a unit of executable code. You can construct a thread on any object that implements runnable. To implement runnable, a class needs to implement a single method called run(), which declared like this:

public void run();

    inside run() you will define the code for the new thread. It is important to understand that the run() method can call other methods, classes and declared a variable just like the main thread. The only difference is that the run() method establishes the entry point for another concurrent thread of execution within your program. This thread will end when run() returns.

    After you create a class that implements Runnable, you will instantiate an object of type Thread from within the class. Thread defines several constructors. The one that we will use is:

Thread(Runnable threadobj, String threadname)

    In this constructor,threadobj is an instance of a class that implements the runnable interface. This defines where the execution of the thread will begin. The name of the new thread is specified in the threadname.

    After the new thread is created, it will not start running until you call its start() method, which is declared within the thread class.The start() method is used to call run().

Sample program to implement Runnable interface:

class ThreadX implements Runnable
{
public void run()
{
for(int i=1;i<=4;i++)
{
System.out.println("ThreadX:"+i);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
ThreadX imprunnable=new ThreadX();
Thread ThreadY=new Thread(imprunnable);
Thread.start();
}
}

The output is:
ThreadX:1
ThreadX:2
ThreadX:3
ThreadX:4


Extending the class thread:

Extending the class is nothing but a class that defines the extended thread class and overrides it's run() method in the subclass. Each thread is a separate instance of the class.

Sample program to create a thread by extending the class thread:
class ThreadX extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println("thread1:"+i)
}
System.out.println("exit from thread1");
}
}
class ThreadY extends Thread
{
public void run()
{
for(int j=1;j<=3;j++)
{
System.out.println("thread2:"+i)
}
System.out.println("exit from thread2");
}
}
class ThreadDemo
{
public static void main(String args[])
{
new ThreadX().start();
new ThreadY().start();
}
}

The output is:

thread1:1
thread1:2
thread2:1
thread2:2
thread2:3
exit from thread2
thread1:3
exit from thread1

The life cycle of a Thread:

A thread moves through several states from its creation to its termination. The life cycles of a thread consist of five states. They are:
-newborn state
-Runnable state
-Running state
-blocked state
-Dead state

The following figure shorts the five states of a thread life cycle:

NewBorn state:

A Thread is said to be the newborn state when we create an object of the Thread class.

Runnable state:

The thread is ready for the execution and waits for the processor to be available. All the thread in an execution queue has equal priority. The thread comes to this state when is start() method is called.

Running state:

The thread comes to this state when it starts its execution. A thread enters this stage whenever it's run() method is called.

Blocked state:

A thread comes to this state when it is made to stop its execution. The thread comes to this state when its stop() or wait() method is called.

Dead state:

A thread comes to this state when it completes its execution.

Also Read:
interface in java



No comments:

Post a Comment