How to create threads in Java?
From main thread we can create our own user defined threads, we can create threads in two ways:
- By extending thread class.
- By implementing run-able interface.
By extending thread class
Create a class which extends thread class. Thread class has two methods run() and start().
In the subclass override run() i.e, write the task which we wanted to execute as a separate thread in run().
In the main() method to start a thread create an object of subclass and call start().
Example:
public class Thread
public static void main(String[] args)
{
System.out.println("main starts");
MyThread1 t1 = new MyThread1();
t1.start()
for(int j=26;j<=50;j++)
{
System.out.println("j=" +j);
try{
Thread.sleep(500);
}
catch(Interrupted exception e)
{
e.PrintStackTrace();
}
}
System.out.println("main ends");
}
}
Class MyThreads extends thread
{
public void run()
{
System.out.println("My Thread1 starts");
for(int i=1;i<=25;i++)
{
System.out.println("i ="+i);
try{
Thread.sleep(500);
}
catch(Interrupted exception e)
{
e.PrintStackTrace();
}
}
System.out.println("My Thread1 ends")
}
By implementing run-able interface
- Create a class which implements run-able.
- Run-able has one abstract method run().
- In the subclass override run method and complete it i.e, write the code which you wanted to execute as a separate code.
- Create an object of type run-able and create an object of type thread by inputting run-able object.
- To start thread invoke start method of thread object.
Example:
public class Run
{
public static void main(String[] args)
{
Runable e1 = new Job1();
Thread t1 = new Thread(r1);
t1.start();
}
}
class Job1 implements Runnable
{
public void run()
{
System.out.println("Thread1 Start");
for(int i=1;i<=25;i++)
{
System.out.println("i ="+i);
}
}
}
0 Comment(s)