Thread class and Runner interface
There are two ways to implement multithreading in Java
- Inherit the Thread class
Pros: You can change the behavior of threads by overriding the thread class's methods.
- Implementing the Runner Interface
Pros: You do not need to inherit the thread class, you can inherit other classes.
Package Threads.samples3; Public classThreadTest { Public Static void Main(string[] args) {//Create an instance of the Thread subclassThread1 T1 =New Thread1();//Create an instance of a class that implements the Runnable interface, passing it as a parameter to an instance of the Thread classThread t2 =NewThread (New Runnable1());//Start thread by calling the Start methodT1.Start(); T2.Start(); }}classThread1extendsThread {@Override Public void Run() { for(inti =0; I <3; i++) {Try{Thread.Sleep( +); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println(i +"in Thread1"); } }}classRunnable1ImplementsRunnable {@Override Public void Run() { for(inti =0; I <3; i++) {Try{Thread.Sleep( +); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println(i +"in Runnable1"); } }}/*0 in Thread10 in Runnable11 in Runnable11 in Thread12 in Runnable12 in Thread1*/
Multithreading (Java)