Java的三种多线程
项目结构
继承Thread类
/* * Thread类实现了Runnable接口 */ public class MyThread extends Thread { @Override public void run() { for(int i=0;i<50;i++){ System.out.println("MyThread子线程 : "+Thread.currentThread().getName()+"~~~"+i); } } }
实现Runnable接口
public class MyRunnable implements Runnable { @Override public void run() { for(int i=0;i<50;i++){ System.out.println("MyRunnable子线程 : "+Thread.currentThread().getName()+"~~~"+i); } } }
实现Callable<T>接口
import java.util.concurrent.Callable; /* * FutureTask<V>类实现了RunnableFuture<V>接口, * RunnableFuture<V>接口实现了Runnable接口、Future<V>接口。 * FutureTask<V>对象的get方法:等待计算完成,然后获取其结果。 */ public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for(int i=0;i<100;i++){ sum += i; System.out.println("MyCallable子线程中间结果 : "+sum); } return sum; } }
运行
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Test { public static void main(String[] args) throws Exception { System.out.println("主线程 : "+Thread.currentThread().getName()); MyThread thread = new MyThread(); MyRunnable runnable = new MyRunnable(); Thread thread2 = new Thread(runnable); MyCallable callable = new MyCallable(); FutureTask<Integer> task = new FutureTask<Integer>(callable); Thread thread3 = new Thread(task); thread.start(); thread2.start(); thread3.start(); int sum = task.get(); System.out.println("MyCallable子线程最终结果 : " + sum); // 这段代码总是最后执行 } }