In programming, threading is a way of distributing our work. We can delegate a huge load of work in to several threads (i.e several processes). A thread will run as a separate operating system process which can run concurrently with other threads.
There are three ways of creating threads in java
To execute code in a separate thread,
There are three ways of creating threads in java
1. Extend the thread class
Thread class has a run method and need override method with the code to run in a its own thread.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Runner extends Thread{ | |
@Override | |
public void run() { | |
for(int i=0;i<10;i++){ | |
System.out.println("Hello "+i); | |
try{ | |
Thread.sleep(100); | |
}catch(InterruptedException e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public class App { | |
public static void main(String args[]){ | |
Runner runner1= new Runner(); | |
runner1.start(); | |
Runner runner2 = new Runner(); | |
runner2.start(); | |
} | |
} |
- Instantiate an object of class which is extended by Thread class (Runner)
- Invoke the start() method of Thread class.
- start() method will go to Thread class and look for the run method and invoke that in a separate thread.
2. Implement Runnable interface
- Implement Runnable interface in a class
- Pass object of that class to a constructor of Thread class.
- Invoke the start() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Runner implements Runnable{ | |
@Override | |
public void run() { | |
for(int i=0;i<10;i++){ | |
System.out.println("Hello "+i); | |
try{ | |
Thread.sleep(100); | |
}catch(InterruptedException e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public class App { | |
public static void main(String args[]){ | |
Thread t1 = new Thread(new Runner()); | |
Thread t2 = new Thread(new Runner()); | |
t1.start(); | |
t2.start(); | |
} | |
} |
3. Instantiate a Thread object with a Runnable instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class App2 { | |
public static void main(String args[]){ | |
Thread t1 = new Thread(new Runnable(){ | |
@Override | |
public void run() { | |
for(int i=0;i<10;i++){ | |
System.out.println("Hello "+i); | |
try{ | |
Thread.sleep(100); | |
}catch(InterruptedException e){ | |
e.printStackTrace(); | |
} | |
} | |
} | |
}); | |
t1.start(); | |
} | |
} |