Java 实现多线程的几种方式汇总
程序员文章站
2024-03-09 08:06:35
我们先来看段示例代码
import java.util.concurrent.callable;
import java.util.concurrent.fut...
我们先来看段示例代码
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().getname() + " " + i); // if (i == 5) { // threadextendsthread threadextendsthread = new threadextendsthread(); // threadextendsthread.start(); // } // } //方法二:实现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(); // } // } //方法三:实现callable接口 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(); } } }
接下来我们来详细探讨下java 实现多线程的几种方式
方法一,继承自thread
public class threadextendsthread extends thread { private int i; @override public void run() { for(; i < 100; i++) { system.out.println(getname() + " " + i); } } }
run方法为线程执行体,threadextendsthread对象即为线程对象。
方法二,实现runnable接口
public class threadimplementsrunnable implements runnable { private int i; @override public void run() { for(; i < 100; i++){ system.out.println(thread.currentthread().getname() + " " + i); } } }
run方法为线程执行体,使用时new一个thread对象,runnable对象作为target传递给thread对象。且同一个runnable对象可作为多个thread的target,这些线程均共享runnable对象的实例变量。
方法三,实现callable接口
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; } }
callable接口类似于runnable接口,但比对方强大,线程执行体为call方法,该方法具有返回值和可抛出异常。使用时将callable对象包装为futuretask对象,通过泛型指定返回值类型。可稍候调用futuretask的get方法取回执行结果。