盘点一下Java中创建线程的几种方式
一、继承Thread类,重写run()方法
public class MyThread extends Thread {@Overridepublic void run() {System.out.println("my thread start " + Thread.currentThread().getName());}public static void main(String[] args) {System.out.println("main thread start "+Thread.currentThread().getName());MyThread myThread = new MyThread();myThread.start();} }
二、实现Runnable接口,并重写run()方法
public class MyThreadRunnable implements Runnable {@Overridepublic void run() {System.out.println("my thread start " + Thread.currentThread().getName());}public static void main(String[] args) {System.out.println("main thread start " + Thread.currentThread().getName());MyThreadRunnable myThreadRunnable = new MyThreadRunnable();Thread thread = new Thread(myThreadRunnable);thread.start();} }
三、实现Callable接口,并重写call()方法
public class MyThreadCallable implements Callable<Integer> {@Overridepublic Integer call() throws Exception {System.out.println("my thread start " + Thread.currentThread().getName());Integer ret = 0;for (int i = 0; i < 10; i++) {ret += i;}return ret;}public static void main(String[] args) throws ExecutionException, InterruptedException {MyThreadCallable myThreadCallable = new MyThreadCallable();FutureTask<Integer> futureTask = new FutureTask<>(myThreadCallable);Thread thread = new Thread(futureTask, "A");thread.start();int ret = futureTask.get();System.out.println("main thread ret = " + ret + " " + Thread.currentThread().getName());} }
综上,类图关系如下: