Four ways to create Thread in java

Three methods of creating threads in
Java and the difference Java uses the Thread class to represent threads. All thread objects must be instances of the Thread class or its subclasses. Java can create threads in three ways, as follows:

1)继承Thread类创建线程

2)实现Runnable接口创建线程

3)使用Callable和Future创建线程(JDK1.5的新增创建线程方法)

4) 使用线程池(JDK1.5的新增创建线程方法)
  1. Inherit the Thread class to create a thread
(1)定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务。因此把run()方法称为执行体。

(2)创建Thread子类的实例,即创建了线程对象。

(3)调用线程对象的start()方法来启动该线程。
  1. By implementing the Runnable interface
1.创建一个实现了Runnable接口的类

2.实现类去实现Runnable中的抽象方法: run( )

3.创建实现类的对象

4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象

5.通过Thread类的对象调用start()

  1. Create threads through Callable and Future (new thread creation method in JDK1.5)
(1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。

(2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

(3)使用FutureTask对象作为Thread对象的target创建并启动新线程。

(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
  1. Use thread pool (new thread creation method of JDK1.5)
使用线程池创建线程的步骤:

    (1)使用Executors类中的newFixedThreadPool(int num)方法创建一个线程数量为num的线程池

    (2)调用线程池中的execute()方法执行由实现Runnable接口创建的线程;调用submit()方法执行由实现Callable接口创建的线程

    (3)调用线程池中的shutdown()方法关闭线程池

Comparison of four methods of creating threads

实现Runnable和实现Callable接口的方式基本相同,不过是后者执行call()方法有返回值,后者线程执行体run()方法无返回值,并且如果使用FutureTask类的话,只执行一次Callable任务。因此可以把这两种方式归为一种这种方式与继承Thread类的方法之间的差别如下:

1、线程只是实现Runnable或实现Callable接口,还可以继承其他类。

2、这种方式下,多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。

3.继承Thread类只需要this就能获取当前线程。不需要使用Thread.currentThread()方法

4、继承Thread类的线程类不能再继承其他父类(Java单继承决定)。

5、前三种的线程如果创建关闭频繁会消耗系统资源影响性能,而使用线程池可以不用线程的时候放回线程池,用的时候再从线程池取,项目开发中主要使用线程池的方式创建多个线程。

6.实现接口的创建线程的方式必须实现方法(run()  call())。

Guess you like

Origin blog.csdn.net/qq_2662385590/article/details/109943328