Thread Using Thread Class
Step 1
Create a class that extends thread class and write your functionality in it.
public class Sam extends Thread { public void print() { for (int i = 1; i <= 10; i++) { System.out.println(i); } } }
Step 2:
Override run method from Thread class and invoke a functionality that to be run as thread. Also added a sleep method to see the difference in thread execution.
public class Sam extends Thread { public void print() { for (int i = 1; i <= 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("from Sam : " + i); } } public void run() { print(); } }
Step 3
Create a main method and test your Thread.
public static void main(String[] args) { Sam s1 = new Sam(); s1.start(); for (int i = 11; i <= 20; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("from Main : " + i); } }
Step 4:
Run the above main method and check the output