Java implements multithreading in three ways, java in three ways
Import java. util. concurrent. callable; import java. util. concurrent. futureTask; public class Main {public static void main (String [] args) {// Method 1: Inherit Thread int I = 0; // for (; I <100; I ++) {// System. out. println (Thread. currentThread (). getName () + "" + I); // if (I = 5) {// ThreadExtendsThread threadExtendsThread = new ThreadExtendsThread (); // threadExtendsThread. start (); //} // Method 2: Implement Runnable // for (I = 0; I <100; I ++) {// System. out. println (Thread. currentThread (). getName () + "" + I); // if (I = 5) {// Runnable runnable = new ThreadImplementsRunnable (); // new Thread (runnable ). start (); // new Thread (runnable ). start (); //} // method 3: implement the Callable interface Callable <Integer> callable = new ThreadImplementsCallable (); futureTask <Integer> futureTask = new FutureTask <> (callable); for (I = 0; I <100; I ++) {System. out. println (Thread. currentThread (). 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 ();}}}
Method 1, inherited from Thread
public class ThreadExtendsThread extends Thread { private int i; @Override public void run() { for(; i < 100; i++) { System.out.println(getName() + " " + i); } }}
The run method is the thread execution body, and the ThreadExtendsThread object is the thread object.
Method 2: implement the Runnable interface
public class ThreadImplementsRunnable implements Runnable { private int i; @Override public void run() { for(; i < 100; i++){ System.out.println(Thread.currentThread().getName() + " " + i); } }}
The run method is the Thread execution body. A New Thread object is used, and the Runnable object is passed to the Thread object as the target object. The same Runnable object can be used as the target of multiple threads. All these threads share the instance variables of the Runnable object.
Method 3: implement the Callable Interface
import java.util.concurrent.Callable;public class ThreadImplementsCallable implements Callable<Integer> { private int i; @Override public Integer call() throws Exception { for(; i < 100; i++){ System.out.println(Thread.currentThread().getName() + " " + i); } return i; }}
The Callable interface is similar to the Runnable interface, but is more powerful than the other party. The thread execution body is the call method. This method has the returned value and can throw an exception. When used, the Callable object is encapsulated as a FutureTask object, and the return value type is specified through generics. You can call the get method of FutureTask to retrieve the execution result later.