一、多线程的三种实现方法
1、继承Thread类
public class MyThread extends Thread { @Override public void run() { try { Thread.sleep(1000); System.out.println("我是Thread"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); System.out.println("结束main"); } }
2、实现Runnable接口
public class MyRunnable implements Runnable { @Override public void run() { try { Thread.sleep(1000); System.out.println("我是runnable"); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); new Thread(myRunnable).start(); System.out.println("结束main"); } }
3、实现Callable接口
public class MyCallable implements Callable<Object> { @Override public Object call() throws Exception { Thread.sleep(1000); System.out.println("我是Callabel"); return "我是Callabel"; } public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newCachedThreadPool(); MyCallable myCallable = new MyCallable(); pool.submit(myCallable); // Future<Object> f = pool.submit(myCallable); // System.out.println(f.get().toString()); System.out.println("main结束"); } }
注:当用Future去接收call()返回值,该方法是阻塞的,即先打印“我是Callable”再打印“main结束”