我们先来看段示例代码
استيراد java.util.concurrent.callable ؛ import java.util.concurrent.futureTask ؛ الفئة العامة الرئيسية {public static void main (string [] args) {// 方法一 : thread int i = 0 ؛ i) ؛ // if (i == 5) {// threadextendsthread threadextendsThread = new threadextendsthread () ؛ // threadextendsthread.start () ؛ //} //} // 方法二 : : 实现 实现 : 实现 实现 实现 实现 实现 实现 实现 实现 实现 实现 实现 实现 : : : : : : :. i) ؛ // if (i == 5) {// RunNable RunNable = new threadimplementsrunnable () ؛ // new thread (runnable) .start () ؛ // new thread (runNable) .start () ؛ //} //} // : : : callable 接口 call 接口 call <teger> callable = new threadimpletscall () ؛ FutureTask <integer> futureTask = new FutureTask <> (Callable) ؛ لـ (i = 0 ؛ i <100 ؛ i ++) {system.out.println (thread.currentThRead (). getName () + "" + i) ؛ if (i == 5) {new thread (futureTask) .start () ؛ موضوع جديد (futureTask) .start () ؛ }} try {system.out.println ("futureTask ruturn:" + futureTask.get ()) ؛ } catch (استثناء e) {E.PrintStackTrace () ؛ }}}接下来我们来详细探讨下 جافا 实现多线程的几种方式
方法一 , 继承自 الخيط
يمتد ThreadextendSTherSthread من الفئة العامة. Override public void run () {for (؛ i <100 ؛ i ++) {system.out.println (getName () + "" + i) ؛ }}}تشغيل 方法为线程执行体 , threadextendsthread 对象即为线程对象。
方法二 , 实现 Runnable 接口
الطبقة العامة threadimplementsrunnable الأدوات runnable {private int i ؛ Override public void run () {for (؛ i <100 ؛ i ++) {system.out.println (thread.currentThread (). getName () + "" + i) ؛ }}}قم بتشغيل 方法为线程执行体 , new 一个 thread 对象 , runnable 对象作为 الهدف 传递给 الخيط 对象。且同一个 Runnable 对象可作为多个 thread 的 target , 这些线程均 共 享 享 对象的实例变量。 对象的实例变量。
方法三 , 实现 callable 接口
استيراد java.util.concurrent.callable ؛ فئة public threadimplementscallable الأدوات القابلة للاتصال <integer> {private int i ؛ Override Public Integer Call () يلقي الاستثناء {for (؛ i <100 ؛ i ++) {system.out.println (thread.currentThRead (). getName () + "" + i) ؛ } العودة أنا ؛ }}callable 接口类似于 接口类似于 接口 , 但比对方强大 , 线程执行体为 call 方法 , 该方法具有返回值和可抛出异常。使用时将 该方法具有返回值和可抛出异常。使用时将 callable 对象包装为 futureTask 对象 , 通过泛型指定返回值类型。可稍候调用 futureTask 的 get 方法取回执行结果。