实现线程的三种方法:
第一种、继承 extends Thread 覆盖 run()方法
public class ThreadA extends Thread { @Override public void run() { try { Thread.sleep(500L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("这是线程A"); } } 执行线程如下:TheadMain public class ThreadMain { public static void main(String[] args) { ThreadA threadA = new ThreadA(); threadA.start(); System.out.println("这是主线程"); } }
注:这个方法有个缺点,一个java类智能继承一个父类
第二种、实现 implements Runnable 接口 实现 run()方法
public class ThreadB implements Runnable { @Override public void run() { try { //模拟做事情执行了500ms Thread.sleep(10000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("这是线程B"); } }
执行线程:
public class ThreadMain { public static void main(String[] args) { ThreadB threadB = new ThreadB(); new Thread(threadB).start();//这里的启动方式有点不一样 System.out.println("这是主线程"); } }
第三种、实现 implements Callable 接口 实现 call()方法可以得到线程执行结果
public class ThreadC implements Callable { @Override public Object call() throws Exception { try { Thread.sleep(500L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("这是线程B"); return "Thread B"; } }
执行线程:
public class ThreadMain { public static void main(String[] args) { ThreadC threadC = new ThreadC(); FutureTask<String> futureTask = new FutureTask<String>(threadC); new Thread(futureTask).start(); System.out.println("这是主线程 begin"); try { System.out.println("得到返回结果:"+futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }