继承Thread类 继承Thread类,重写run()方法。
1 2 3 4 5 6 7 8 9 10 11 public class ExtendThread extends Thread { @Override public void run () { super .run(); System.out.println("this is sub thread extends from Thread" ); } public static void main (String[] args) { new ExtendThread ().start(); } }
java中是单继承,如果使用这种方式的话,每个类即是一个线程。
实现Runnable接口 重写run()方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class RunnableThread implements Runnable { @Override public void run () { System.out.println("this is thread implements Runnable" ); } public static void main (String[] args) { Runnable runnable = new RunnableThread () ; new Thread (runnable).start(); } }
Callable+Future先看下Callable接口的定义
1 2 3 4 5 6 7 8 9 10 public interface Callable <V> { V call () throws Exception; }
再来看下Future
1 2 3 4 5 6 7 8 public interface Future { boolean cancel (boolean mayInterruptIfRunning) ; boolean isCancelled () ; boolean isDone () ; V get () throws InterruptedException, ExecutionException; V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
我们一般配合线程池来使用,因为:
1 ` Future submit (Callable task) ;`` Future submit (Runnable task, T result) ;``Future submit (Runnable task) ;`
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public class CallableThread implements Callable <Integer> { @Override public Integer call () throws Exception { int sum = 0 ; for (int i=0 ; i<100 ; i++) sum += i ; return sum; } public static void main (String[] args) throws ExecutionException, InterruptedException { ExecutorService service = new ThreadPoolExecutor (5 ,10 ,60L , TimeUnit.SECONDS,new ArrayBlockingQueue (10 )); Future future = service.submit(new CallableThread ()) ; System.out.println(future.get()); } }
上面实现Runnable接口已经比继承自Thread类的实现方法更为优雅了,但是这种方法还有一个问题,就是无法获得子线程的执行结果。这时候就需要Callable接口,它和Runnable接口效果差不多,唯一不同的是有返回值。这里配合Future来接收。
Callable+FutureTaskFutureTask
1 public class FutureTask <V> implements RunnableFuture <V>
1 public interface RunnableFuture <V> extends Runnable , Future<V>
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class FutureTaskThread implements Callable <Integer> { @Override public Integer call () throws Exception { int sum = 0 ; for (int i=0 ; i<100 ; i++) sum += i ; return sum; } public static void main (String[] args) { FutureTask futureTask = new FutureTask (new FutureTaskThread ()) ; ExecutorService service = new ThreadPoolExecutor (5 ,10 ,60L , TimeUnit.SECONDS,new ArrayBlockingQueue <>(10 )); service.submit(futureTask) ; try { System.out.println(futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }