Let's take a look at the snippet sample code first
Import java.util.concurrent.Callable;
Import Java.util.concurrent.FutureTask; public class Main {public static void main (string[] args) {//Method one: inheriting thread int i = 0;//for (; i < 100;
i++) {//System.out.println (Thread.CurrentThread (). GetName () + "" + i); if (i = = 5) {//Threadextendsthread Threadextendsthread = new Threadextendsthread ();//Threadexten
Dsthread.start (); ////Method Two: Implement Runnable//for (i = 0; i < i++) {//System.out.println (THREAD.CURRENTTH
Read (). GetName () + "" + i); if (i = = 5) {//Runnable Runnable = new threadimplementsrunnable ();//New Thread (Runnable). Start ()
;
New Thread (runnable). Start ();
////Method III: Implement callable interface callable<integer> callable = new threadimplementscallable ();
futuretask<integer> futuretask = new futuretask<> (callable); for (i = 0; i < i++) {System.out.println (THREAD.CURRENTTHR)EAD (). GetName () + "" + i);
if (i = = 5) {new Thread (Futuretask). Start ();
New Thread (Futuretask). Start ();
} try {System.out.println ("Futuretask ruturn:" + futuretask.get ());
catch (Exception e) {e.printstacktrace ();
}
}
}
Next, we'll discuss several ways to implement multithreading in Java in detail
Method one, inheriting from thread
public class Threadextendsthread extends Thread {
private int i;
@Override public
Void Run () {for
(; i < i++) {System.out.println (
getName () + "" + i);
}
}
}
The Run method is the thread executor, and the Threadextendsthread object is the thread object.
Method Two, implement Runnable interface
public class Threadimplementsrunnable implements Runnable {
private int i;
@Override public
Void Run () {for
(; i < i++) {
System.out.println thread.currentthread (). GetName () + "" + i);
}}}
The Run method is the thread executor, and the new thread object is used, and the Runnable object is passed to the thread object as target. And the same Runnable object can be target for multiple threads, which share instance variables of the Runnable object.
Method Three, realize callable interface
Import java.util.concurrent.Callable;
public class Threadimplementscallable implements callable<integer> {
private int i;
@Override public
Integer call () throws Exception {for
(; i < i++) {
System.out.println ( Thread.CurrentThread (). GetName () + "" + i);
}
return i;
}
}
The callable interface is similar to the Runnable interface, but stronger than the other, the thread execution body is the call method, which has a return value and can throw an exception. Wraps the callable object as a Futuretask object when used, specifying the return value type by generics. You can call the Futuretask get method to retrieve the execution results at a later moment.