Thread、Runnable、Callable三种实现方式
Thread
public class ThreadDemo extends Thread { public static void main(String[] args) { ThreadDemo threadDemo = new ThreadDemo(); threadDemo.setName("ThreadDemo"); threadDemo.start(); } }
Runnable
public class RunnableDemo { public static void main(String[] args) { RunnableThread runnableThread = new RunnableThread(); Thread thread = new Thread(runnableThread); thread.setName("RunnableThread"); thread.start(); } } class RunnableThread implements Runnable { public void run() { System.out.println("execute RunnableThread"); } }
Callable
public class CallableDemo { public static void main(String[] args) { ExecutorService thread = Executors.newSingleThreadExecutor(); try { CallableThread callableThread = new CallableThread(); Future<Integer> future = thread.submit(callableThread); Integer result = future.get(); System.out.println("Result=" + result); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } finally { if (thread != null && !thread.isShutdown()) { thread.shutdown(); } } } } class CallableThread implements Callable<Integer> { @Override public Integer call() throws Exception { return 100; } }
收藏文章数量从多到少与“把书读薄”是一个道理