MultiThread in java
MultiThread is a to execute the two or more thread in same time.
The use of Multithread
MultiThread is important topic. Because If you want to be a game developer you must know about this.
For Example , you just Imagine play the pubg game , you just move forward , at the same time the opponent also moving .At the once time two or more players moving , how to do this. If you use multiThread you can do this very simple.
Example-1
class A extends Thread { public void run() { for (int i=0;i<5;i++) { System.out.println("Class A"); try { Thread.sleep(500); } catch(Exception e){} } } } class B extends Thread { public void run() { for (int i=0;i<5;i++) { System.out.println("Class B"); try { Thread.sleep(500); } catch(Exception e){} } } } public class Main { public static void main(String[] args) { A obj1 = new A(); B obj2 = new B(); obj1.start(); try { Thread.sleep(500); } catch(Exception e){} obj2.start(); } }
Output
Class A Class B Class A Class B Class A Class B Class A Class B Class A Class B
Example-2
class A implements Runnable { public void run() { for (int i=0;i<5;i++) { System.out.println("Class A"); try { Thread.sleep(500); } catch(Exception e){} } } } class B implements Runnable { public void run() { for (int i=0;i<5;i++) { System.out.println("Class B"); try { Thread.sleep(500); } catch(Exception e){} } } } public class Main { public static void main(String[] args) { Runnable obj1 = new A(); Runnable obj2 = new B(); Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); t1.start(); try { Thread.sleep(10); } catch(Exception e){} t2.start(); } }
Output
Class A Class B Class A Class B Class A Class B Class A Class B Class A Class B