Importjava.util.concurrent.Callable;ImportJava.util.concurrent.FutureTask; Public classMain { Public Static voidMain (string[] args) {//method One: Inherit thread inti = 0;//For (; i < i++) {//System.out.println (Thread.CurrentThread (). GetName () + "" + i);//if (i = = 5) {//threadextendsthread threadextendsthread = new Threadextendsthread ();//Threadextendsthread.start ();// }// } //method Two: Realize runnable//For (i = 0; i <; i++) {//System.out.println (Thread.CurrentThread (). GetName () + "" + i);//if (i = = 5) {//Runnable Runnable = new threadimplementsrunnable ();//new Thread (runnable). Start ();//new Thread (runnable). Start ();// }// } //method Three: Implement callable interfaceCallable<integer> callable =Newthreadimplementscallable (); Futuretask<Integer> Futuretask =NewFuturetask<>(callable); for(i = 0; i < i++;) {System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); if(i = = 5) { NewThread (Futuretask). Start (); NewThread (Futuretask). Start (); } } Try{System.out.println ("Futuretask Ruturn:" +futuretask.get ()); } Catch(Exception e) {e.printstacktrace (); } }}
Method one, inherited from thread
Public class extends Thread { privateint i; @Override publicvoid run () { for (; I < i++) { + "" + i); }}}
The Run method is the thread execution body, and the Threadextendsthread object is the thread object.
Method Two, implement the Runnable interface
Public class Implements Runnable { privateint i; @Override publicvoid run () { for (; I < i++) { + "" + i); }}}
The Run method is the thread execution body, using the new thread object as the Runnable object, which is passed as target to the thread object. And the same Runnable object can serve as a target for multiple threads that share instance variables of the Runnable object.
Method Three, implement callable interface
import java.util.concurrent.Callable; public class threadimplementscallable implements callable<integer> { private int I; @Override public Integer call () throws
Exception { for (; <; i++) {System.out.println (Thread.CurrentThread (). GetName () + "+ i); return I; }}
The callable interface is similar to the Runnable interface, but is stronger than the other, and the thread execution body is the call method, which has a return value and an exception that can be thrown. When used, wraps the callable object as a Futuretask object, specifying the return value type by generic type. You can call Futuretask's Get method later to retrieve the execution result.
Three ways to implement multithreading in Java