详解Java创建多线程的四种方式以及优缺点

2022-07-27,,,,

java有以下四种创建多线程的方式

1:继承thread类创建线程

2:实现runnable接口创建线程

3:使用callable和futuretask创建线程

4:使用线程池,例如用executor框架创建线程

demo代码

package thread;
 
import java.util.concurrent.*;
 

public class threadtest {
 public static void main(string[] args) throws executionexception, interruptedexception {
//  创建线程的第一种方法
  thread1 thread1 = new thread1();
  thread1.start();
 
//  创建线程的第二种方法
  thread2 thread2 = new thread2();
  thread thread = new thread(thread2);
  thread.start();
 
//  创建线程的第三种方法
  callable<string> callable = new thread3();
  futuretask<string> futuretask = new futuretask<>(callable);
  thread thread3 = new thread(futuretask);
  thread3.start();
  string s = futuretask.get();
  system.out.println(s);
 
//  创建线程的第四种方法
  executor executor = executors.newfixedthreadpool(5);
  executor.execute(new runnable() {
   @override
   public void run() {
    system.out.println(thread.currentthread()+"创建线程的第四种方法");
   }
  });
  ((executorservice) executor).shutdown();
 
 }
}
class thread1 extends thread{
 @override
 public void run() {
  system.out.println(thread.currentthread()+"创建线程的第一种方法");
 }
}
 
class thread2 implements runnable {
 
 @override
 public void run() {
  system.out.println(thread.currentthread()+"创建线程的第二种方法");
 }
}
 
class thread3 implements callable<string> {
 
 @override
 public string call() throws exception {
  return thread.currentthread()+"创建线程的第三种方法";
 }
}

创建线程的三种方式的对比

1、采用实现runnable、callable接口的方式创建多线程

  优势:

   线程类只是实现了runnable接口或callable接口,还可以继承其他类。

   在这种方式下,多个线程可以共享同一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将cpu、代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。

   劣势:

 编程稍微复杂,如果要访问当前线程,则必须使用thread.currentthread()方法。

2、使用继承thread类的方式创建多线程

  优势:

  编写简单,如果需要访问当前线程,则无需使用thread.currentthread()方法,直接使用this即可获得当前线程。

  劣势:

  线程类已经继承了thread类,所以不能再继承其他父类。

3、runnable和callable的区别

runnable接口定义的run方法,callable定义的是call方法。
run方法没有返回值,call方法必须有返回值。
run方法无法抛出异常,call方法可以抛出checked exception。
callable和runnable都可以应用于executors。而thread类只支持runnable.

总结

鉴于上面分析,因此一般推荐采用实现runnable接口、callable接口的方式来创建多线程。

到此这篇关于java创建多线程的四种方式以及优缺点的文章就介绍到这了,更多相关java创建多线程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《详解Java创建多线程的四种方式以及优缺点.doc》

下载本文的Word格式文档,以方便收藏与打印。