java multithreading
We can define java multithreading in the following two ways:-
- By extending Thread class
- By implementing Runable interface
1. By extending Thread class:-
example:-
class MyThread extends Thread
{
public void run ()//This for run method will be executed by child thread
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread");
}
}
}
class ThreadDemo
{
public static void main(String [] args)
{
MyThread t =new MyThread();
t.start();// starting of thread
for(int i=0;i<10;i++)
{
System.out.println("Main Thread");//This for Loop will be executed by main thread
}
}
}
run method:-
run method present is thread class and it has an empty implementation. child thread is responsible for executing run method. So we have to override the thread class run method in our java program. If we don't override run method then it's super class means thread class run method will be called and it has empty implementation so no output will be produced.