创建线程的几种方法

可以算作四种吧。

一、继承Thread类创建线程

不推荐这种方法。

一般步骤如下

  • 定义Thread类的子类,并重写该类的run()方法,该方法的方法体就是线程需要完成的任务,run()方法也称为线程执行体。
  • 创建Thread子类的实例,也就是创建了线程对象
  • 启动线程,即调用线程的start()方法
public class MyThread extends Thread{//继承Thread类
 
  public void run(){
  //重写run方法
  }
}
 
public class Main {
  public static void main(String[] args){
    new MyThread().start();//创建并启动线程
  }
}

二、实现Runnable接口创建线程

通过实现Runnable接口创建并启动线程一般步骤如下:

  • 定义Runnable接口的实现类,一样要重写run()方法,这个run()方法和Thread中的run()方法一样是线程的执行体

  • 创建Runnable实现类的实例,并用这个实例作为Thread的target来创建Thread对象,这个Thread对象才是真正的线程对象

  • 第三部依然是通过调用线程对象的start()方法来启动线程

补充下,Thread类就是Runnable接口的实现类,Thread类有一个非常重要的构造方法:

package java.lang;

public class Thread implements Runnable {
  	public Thread (Runnable target);
}

它传入一个Runnable接口的实例,在start()方法调用时,新的线程就会执行Runnable.run()方法。实际上,默认的Thread.run()方法就是这么做的。

public void run() {
  if (target != null) {
 		target.run();
  }
} 

默认的Thread.run()方法就是直接调用内部的Runnable接口。因此,使用Runnable接口告诉线程该做什么,更为合理。

案例:

public class MyThread2 implements Runnable {//实现Runnable接口
 
  public void run(){
  //重写run方法
 
  }
}
 
public class Main {
  public static void main(String[] args){
    //创建并启动线程
    MyThread2 myThread = new MyThread2();
    Thread thread = new Thread(myThread);
    thread().start();
    //或者    new Thread(new MyThread2()).start();
  }
}

三、使用Callable和Future创建线程

和Runnable接口不一样,Callable接口提供了一个call()方法作为线程执行体,call()方法比run()方法功能要强大。

Callable接口与jdk5加入,与Runnable接口类似,实现之后代表一个线程任务,Callable具有泛型返回值、可以声明异常。

  public interface Callable<V>{
      public V call() throws Exception;
  }

Java5还提供了Future接口来代表Callable接口里call()方法的返回值,并且为Future接口提供了一个实现类FutureTask,这个实现类既实现了Future接口,还实现了Runnable接口,因此可以作为Thread类的target。在Future接口里定义了几个公共方法来控制它关联的Callable任务。

简单看下FutureTask的源码,有着两个不同的构造方法:

package java.util.concurrent;

public class FutureTask<V> implements RunnableFuture<V> {
     /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
  
     /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     *
     * @param runnable the runnable task
     * @param result the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
  
  	// 视图取消该Future里面关联的Callable任务
  	public boolean cancel(boolean mayInterruptIfRunning) {}

  	//返回Callable里call()方法的返回值,调用这个方法会导致程序阻塞,必须等到子线程结束后才会得到返回值
  	public V get() throws InterruptedException, ExecutionException {}

  	// 返回Callable里call()方法的返回值,最多阻塞timeout时间,经过指定时间没有返回抛出TimeoutException
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {}
  
  	// 若Callable任务完成,返回True
		public boolean isDone() {}

  	// 如果在Callable任务正常完成前被取消,返回True
    public boolean isCancelled() {}
}

案例:需要将Callable对象转换成可执行任务FutureTask(FutureTask 实现了Runnable接口),再传给线程

package com.wlw.thread.threaddemo02;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 演示Callable接口的使用
 * Callable接口与Runnable接口的区别:
 * (1)Callable接口中call方法具有泛型返回值,Runnable接口中的run方法没有返回值
 * (2)Callable接口中call方法有声明异常,Runnable接口中的run方法没有声明异常
 */
public class CallableDemo {
    public static void main(String[] args) throws Exception {
        //功能需求:使用Callable实现1~100的和
        //1.创建Callable对象
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName()+"开始计算:");
                int sum = 0;
                for (int i = 0; i <= 100; i++) {
                    sum = sum + i;
                }
                return sum;
            }
        };

        //2.将Callable对象转换成可执行任务(FutureTask 实现了Runnable接口)
        FutureTask<Integer> task = new FutureTask<>(callable);

        //3.创建线程对象,将任务传给线程
        Thread thread = new Thread(task);

        //4.启动线程
        thread.start();

        //5.获取结果(get() 方法要等call() 方法执行完毕,才能返回)
        Integer integer = task.get();
        System.out.println(integer);
    }
}
/*
执行结果:
Thread-0开始计算:
5050
*/

四、使用线程池例如用Executor框架

线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度。

Java5后引入的Executor框架的最大优点是把任务的提交和执行解耦。要执行任务的人只需把Task描述清楚,然后提交即可。这个Task是怎么被执行的,被谁执行的,什么时候执行的,提交的人就不用关心了。具体点讲,提交一个Callable对象给ExecutorService(如最常用的线程池ThreadPoolExecutor),将得到一个Future对象,调用Future对象的get方法等待执行结果就好了。Executor框架的内部使用了线程池机制,它在java.util.cocurrent 包下,通过该框架来控制线程的启动、执行和关闭,可以简化并发编程的操作。因此,在Java 5之后,通过Executor来启动线程比使用Thread的start方法更好,除了更易管理,效率更好(用线程池实现,节约开销)外,还有关键的一点:有助于避免this逃逸问题——如果我们在构造器中启动一个线程,因为另一个任务可能会在构造器结束之前开始执行,此时可能会访问到初始化了一半的对象用Executor在构造器中。

4.1、Executor框架

包括:线程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。

线程池的体系结构:
  java.util.concurrent.Executor : 负责线程的使用与调度的根接口
     |--**ExecutorService 子接口: 线程池的主要接口
        |--ThreadPoolExecutor 线程池的实现类
        |--**ScheduledExecutorService 子接口:负责线程的调度
           |--ScheduledThreadPoolExecutor :继承 ThreadPoolExecutor, 实现ScheduledExecutorService
  • Executor接口中之定义了一个方法execute(Runnable command),该方法接收一个Runable实例,它用来执行一个任务,任务即一个实现了Runnable接口的类。

  • ExecutorService接口继承自Executor接口,它提供了更丰富的实现多线程的方法。

    • ExecutorService提供了关闭自己的方法, 可以调用ExecutorService的shutdown()方法来平滑地关闭 ExecutorService,调用该方法后,将导致ExecutorService停止接受任何新的任务且等待已经提交的任务执行完成(已经提交的任务会分两类:一类是已经在执行的,另一类是还没有开始执行的),当所有已经提交的任务执行完毕后将会关闭ExecutorService。因此我们一般用该接口来实现和管理多线程。
    • 为跟踪一个或多个异步任务执行状况而生成 Future 的方法。
    • ExecutorService的生命周期包括三种状态:运行、关闭、终止。创建后便进入运行状态,当调用了shutdown()方法时,便进入关闭状态,此时意味着ExecutorService不再接受新的任务,但它还在执行已经提交了的任务,当所有已经提交了的任务执行完后,便到达终止状态。如果不调用shutdown()方法,ExecutorService会一直处在运行状态,不断接收新的任务,执行新的任务,服务器端一般不需要关闭它,保持一直运行即可。

4.2、 工具类 : Executors

提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。

  ExecutorService newFixedThreadPool() : 创建固定大小的线程池
  ExecutorService newCachedThreadPool() : 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。
  ExecutorService newSingleThreadExecutor() : 创建单个线程池。线程池中只有一个线程
  ScheduledExecutorService newScheduledThreadPool() : 创建固定大小的线程,可以延迟或定时的执行任务。   

这四种方法都是用的Executors中的ThreadFactory建立的线程,下面就以上四个方法做个比较

还可以使用自定义线程池,可以用ThreadPoolExecutor类创建,它有多个构造方法来创建线程池,用该类很容易实现自定义的线程池,这里先贴上示例程序:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class ThreadPoolTest {
    public static void main(String[] args) {
        //创建等待队列
        BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<>(4);
        //创建线程池,池中保存的线程数为3,允许的最大线程数为5
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 3, 30, TimeUnit.SECONDS, bqueue);
        //创建七个任务
        Runnable t1 = new MyThread();
        Runnable t2 = new MyThread();
        Runnable t3 = new MyThread();
        Runnable t4 = new MyThread();
        Runnable t5 = new MyThread();
        Runnable t6 = new MyThread();
        Runnable t7 = new MyThread();
        //每个任务会在一个线程上执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        pool.execute(t7);
        //关闭线程池
        pool.shutdown();
    }
}
 
class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "正在执行。。。");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
} 

这里简要说明下用到的ThreadPoolExecuror类的构造方法中各个参数的含义。

  • public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue < Runnable> workQueue)

  • corePoolSize:线程池中所保存的线程数,包括空闲线程。

  • maximumPoolSize:池中允许的最大线程数。

  • keepAliveTime:当线程数大于核心数时,该参数为所有的任务终止前,多余的空闲线程等待新任务的最长时间。

  • unit:等待时间的单位。

  • workQueue:任务执行前保存任务的队列,仅保存由execute方法提交的Runnable任务。

总结

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

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

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

3、但是编程稍微复杂,如果需要访问当前线程,必须调用Thread.currentThread()方法。

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

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

注:在前三种中一般推荐采用实现接口的方式来创建多线程。

创建线程本质只有1种,即创建Thread类,以上的所谓创建方式其实是实现run方法的方式:

实现run方法的方式分为两类,你所看到的其他的都是对这两类的封装:

1、实现runnable接口的run方法,并把runnable实例作为target对象,传给thread类,最终调用target.run

2、继承Thread类,重写Thread的run方法,Thread.start会执行run方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悬浮海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值