There are two ways to create Java threads, and here we learn through simple Examples.
multi-threading creation in Java one, creating multithreading by inheriting the thread class
public classHellothreadextendsThread {@Override public voidRun () {Try{TimeUnit.SECONDS.sleep (1); System.out.println ("Hello from a thread!"); } Catch(interruptedexception E) {e.printstacktrace (); } } public Static voidMain (string[] Args)throwsinterruptedexception {hellothread Hellothread=NewHellothread (); Hellothread.start (); System.out.println ("in Main thread."); }}
The results of the operation are as Follows:
from a thread!
second, by implementing the Runnable interface to create multithreading
public classHellorunnableImplementsRunnable {@Override public voidRun () {Try{System.out.println ("Hello from a thread!"); TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception E) {e.printstacktrace (); } } public Static voidmain (string[] Args) {thread thread=NewThread (Newhellorunnable ()); Thread.Start (); System.out.println ("in Main method."); }}
The results of the operation are as Follows:
from a thread!
Friendship Link
Java Foundation---->java multi-threaded use (i)