多线程创建的三种方式对比
- 继承Thread
- 优点:可以直接使用Thread类中的方法,代码简单
- 缺点:继承Thread类之后就不能继承其他的类
- 实现Runnable接口
- 优点:即时自定义类已经有父类了也不受影响,因为可以实现多个接口
- 缺点: 在run方法内部需要获取到当前线程的Thread对象后才能使用Thread中的方法
- 实现Callable接口
- 优点:可以获取返回值,可以抛出异常
- 缺点:代码编写较为复杂
使用匿名内部类创建线程
package com.sutaoyu.Thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class test_4 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
/*
* Thread
*/
new Thread() { // 1.继承Thread类
public void run() { // 2.重写run方法
for(int i = 0;i<1000;i++) { // 3.将要执行的代码写在run方法中
System.out.println(i + "Thread");
}
}
}.start(); // 4.开启线程
/*
* Runnable
*/
new Thread(new Runnable() { // 1.将Runnable的子类对象传递给Thread的构造方法
public void run() { // 2.重写run方法
for(int i = 0;i < 1000;i++) {
System.out.println( i + "Runnable");
}
}
}).start();// 4.开启线程
/*
* Callable
*/
ExecutorService exec = Executors.newCachedThreadPool();
Future<Integer> result = exec.submit(new Callable<Integer>() {
public Integer call() throws Exception{
return 1024;
}
});
System.out.println(result.get());
}
}