线程有三种实现方式:
- 继承Thread类
- 优点:在类直接this就能获取当前线程
- 缺点:java不支持多继承
-
public class Thread1 extends Thread{ public Thread1(){ this.setName("南方菇凉"); } @Override public void run() { System.out.println("啦啦啦啦啦啦啦"); String name = this.getName(); System.out.println("我是线程-"+name); super.run(); } public static void main(String[] args) { // 创建线程 Thread1 thread1 = new Thread1(); // 启动线程 thread1.start(); } }
- 实现Runable接口
- 优点:java支持多实现
- 缺点:启动之前需要显示的创建线程,调用start方法
-
public class Thread2 implements Runnable { @Override public void run() { System.out.println("南方地小镇"); } public static void main(String[] args) { Thread2 thread2 = new Thread2(); Thread thread = new Thread(thread2); thread.start(); } }
- 使用FutureTask方式
- 优点:可以获取返回值
- 缺点:启动之前需要显示的创建线程,调用start方伐
-
public class Thread3 implements Callable<String> { @Override public String call() throws Exception { return "南方菇凉"; } public static void main(String[] args) { // 创建异步任务 FutureTask<String> stringFutureTask = new FutureTask<>(new Thread3()); new Thread(stringFutureTask).start(); //等待任务执行完毕,并返回结果 String s = stringFutureTask.get(); System.out.println(s); } }