Monday, January 4, 2016

WAYS OF CREATING THREAD IN JAVA


THREAD CREATION IN JAVA


Java is a multi threaded programming language which means we can develop multi threaded program using Java. A multi threaded program contains two or more parts that can run concurrently and each part can handle different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.By definition multitasking is when multiple processes share common processing resources such as a CPU. Multi threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.Multi threading enables you to write in a way where multiple activities can proceed concurrently in the same program.

TYPES OF CREATING THREAD:-


1.      IMPLEMENTING RUNNABLE INTERFACE
2.      EXTENDING THREAD CLASS
3.      ANONMYOUS THREAD CLASS
4.      ANONMYOUS RUNNABLE INTERFACE THREAD
5.      LAMBDA ANONMYOUS RUNNABLE THREAD


TYPE 1-CREATING THREAD USING IMPLEMENTING RUNNABLE INTERFACE


public  class Runnablethre implements Runnable
{
static Thread ti;

Runnablethre()
{
System.out.println("Strating thread..");
}

@Override
public void run()
{
System.out.println("running thread..");
try {
Thread.sleep(100);
System.out.println("NAME OF THE THREAD.."+ti.getName());
System.out.println("PRIORITY OF THE THREAD.."+ti.getPriority());
} catch (InterruptedException ex) {
Logger.getLogger(Runnablethre.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("thread Excited..");
}

public static void main(String args[])
{
Runnablethre re=new Runnablethre();
System.out.println("Creating thread..");
ti=new Thread(re);
ti.start();

} }

TYPE 2-  CREATING THREAD BY EXTENDING THREAD CLASS

public class ExtendThread extends Thread
{
public void run()
{
System.out.println("running thread");
}

public static void main(String args[])
{
Thread t1=new Thread(new ExtendThread());
t1.start();
}

}

TYPE 3-ANONMYOUS THREAD

public class AnonmyThread
{
public static void main(String args[])
{
Thread t1=new Thread()
{
public void run()
{
System.out.println("THREAD CREATED..");
}
};
t1.start();
}

}

TYPE 4- ANONMYOUS RUNNABLE INTERFACE THREAD

public class AnonmyRunn
{
public static void main(String args[])
{
Runnable r1=new Runnable()
{
@Override
public void run() {
System.out.println("THREAD CREATED..");
}

};
Thread t1=new Thread(r1);
t1.start()
}
}

TYPE 5- LAMBDA ANONMYOUS RUNNABLE THREAD

public class lAMBDAthread
{
public static void main(String args[])
{
Runnable task2 = () -> {
System.out.println("Task #2 is running");
};
new Thread(task2).start();
}

}

No comments:

Post a Comment