继承Thread类 重写run方法
class MyThread extends Thread { @Override public void run() { System.out.println("My Thread."); } }
匿名内部类:
Thread t1 = new Thread() { @Override public void run() { System.out.println("Thread t1."); } }; t1.start();
Lambda:
Thread t2 = new Thread(() -> { System.out.println("Thread t2."); }); t2.start();
实现Runnable接口 重写run方法
class MyRunnable implements Runnable { @Override public void run() { System.out.println("My Runnable."); } }
实现Callable重写call方法,配合FutureTask
class MyCallable implements Callable<String> { @Override public String call() throws Exception { return "My Callable."; } } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable callable = new MyCallable(); FutureTask<String> futureTask = new FutureTask<>(callable); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); }
基于线程池构建线程
其实,都是实现Runnable接口。
1、Thread实现Runnable
public class Thread implements Runnable {
2、FutureTask实现了Runnable,run方法调用callable。
public class FutureTask<V> implements RunnableFuture<V> { public interface RunnableFuture<V> extends Runnable, Future<V> { public void run() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); } if (ran) set(result); } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } }
3、线程池创建的Worker也是实现了Runnable。
private final class Worker extends AbstractQueuedSynchronizer implements Runnable