写在之前
深夜水文,聊聊多线程的不同实现方式吧
继承Thread实现
public class ThreadThread extends Thread{
@Override
public void run() {
System.out.println ("Thread实现");
}
public static void main(String[] args) {
ThreadThread threadDemo = new ThreadThread ();
threadDemo.start ();
}
}
优点:代码编写简单
缺点:不能继承其他类拓展性差
实现Runnable接口
public class ThreadRunnable implements Runnable{
@Override
public void run() {
System.out.println ("Runnable方式实现");
}
public static void main(String[] args) {
Thread thread = new Thread (() -> {
System.out.println ("Runnable方式实现");
});
thread.start ();
}
}
优点:可以实现多个接口,可以再继承一个类,拓展性好
缺点:没返回值,不能直接启动
通过callable接口和FutureTask类实现
public class ThreadTask implements Callable {
@Override
public Object call() throws Exception {
System.out.println ("Callable实现");
return "Callable";
}
public static void main(String[] args) {
Thread thread = new Thread (new FutureTask<Object> (new ThreadTask ()));
thread.start ();
}
}
优点:有返回值,拓展性高
缺点:jdk5以后才支持,需要多个类结合实现
线程池实现
public class ThreadPool implements Runnable{
@Override
public void run() {
System.out.println ("线程池实现");
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool (3);
executorService.execute (new ThreadPool ());
executorService.shutdown ();
}
}
优点:安全 性能高
缺点:jdk5以后才支持,需要结合Runnable接口使用
|