我们先来看段示例代码
import java.util.concurrent.callable; import java.util.concurrent.futureTask; public class main {public static void main (String [] args) {// 方法一 : 继承 thread int i = 0; // for (; i <100; i ++) {// system.out.println (thread.currentThread (). i); // if (i == 5) {// ThreadExtStHread ThreadExtendSThread = new ThreadExtStendShread (); // ThreaStendStthread.Start (); //} //} // 方法二 : 实现 runnable // for (i = 0; i <100; i ++) {// System.out.printLnn (Thread.curRentShread (). "+ i); // if (i == 5) {// runnable runnable = new ThreadIMPlementsRunnable (); // new Thread (runnable) .start (); // new Thread (runnable) .start (); //} //} // 方法三 : : 实现 callable 接口 callable <Integer> callable = new ThreadIMPLIMPLESTALLABLE ();); FutureTask <Integer> FutureTask = new FutureTask <> (callable); pour (i = 0; i <100; i ++) {System.out.println (thread.currentThread (). getName () + "" + i); if (i == 5) {nouveau thread (futureTask) .start (); Nouveau thread (FutureTask) .start (); }} essayez {System.out.println ("FutureTask RUTUR:" + FutureTask.get ()); } catch (exception e) {e.printStackTrace (); }}}接下来我们来详细探讨下 Java 实现多线程的几种方式
方法一 , 继承自 Thread
classe publique threadExtendSThread étend Thread {private int i; @Override public void run () {for (; i <100; i ++) {System.out.println (getName () + "" + i); }}}Exécuter 方法为线程执行体 , ThreadExtendSThread 对象即为线程对象。
方法二 , 实现 Runnable 接口
classe publique ThreadImplementsRunnable implémente Runnable {private int i; @Override public void run () {for (; i <100; i ++) {System.out.println (thread.currentThread (). GetName () + "" + i); }}}Exécuter 方法为线程执行体 , 使用时 Nouveau 一个 Thread 对象 , Runnable 对象作为 Target 传递给 Thread 对象。且同一个 Runnable 对象可作为多个 Thread 的 Target , 这些线程均 共 享 Runnable 对象的实例变量。
方法三 , 实现 Callable 接口
import java.util.concurrent.callable; public class threadImplementsCallable implémente callable <Integer> {private int i; @Override public Integer Call () lève une exception {pour (; i <100; i ++) {System.out.println (thread.currentThread (). GetName () + "" + i); } return i; }}Callable 接口类似于 Runnable 接口 , 但比对方强大 , 线程执行体为 Appelez 方法 , 该方法具有返回值和可抛出异常。使用时将 CALLable 对象包装为 FutureTask 对象 , 通过泛型指定返回值类型。可稍候调用 Futuretask 的 Get 方法取回执行结果。