Java线程

zlong.w Lv2

创建线程的方式

  1. 继承Thread类,重新run()方法。 没有返回值。
  2. 实现Runnable接口,重新run()方法。 没有返回值
  3. 实现Callable接口,重写call()方法,利用FutureTask包装Callable,并作为task传入Thread构造函数。
    有返回值
  4. 利用线程池

具体的实现

  1. 继承Thread类,重新run()方法。 没有返回值。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class Threimp extends Thread{
    @Override
    public void run() {
    for (int i = 0; i <= 100; i ++) {
    System.out.println("线程内部输出---->" + i);
    }
    }
    public static void main(String[] args) {
    Threimp im = new Threimp();
    im.start();
    }
    }
  • Thread类本质上是实现了Runnable接口,Thread对象代表一个线程的实例
  • Runnable接口只有一个抽象的run()方法
  • 启动线程的唯一方法就是通过Thread类的start()方法
  • start()方法是一个native方法,它将启动一个新线程并执行run()方法
  1. 实现Runnable接口,重写run()方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class Three implements Runnable{
    @Override
    public void run() {
    for (int i = 0; i < 100; i++) {
    System.out.println("Runnable线程内部输出---->"+i);
    }
    }
    //将Runnable作为参数传入Thread的构造函数中,创建Thread
    public static void main(String[] args) {
    Thread tf = new Thread(new Three());
    tf.start();
    }
    }
  2. 现Callable接口,重写call()方法
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class CallableImpl implements Callable<Integer> {
    private static Integer a = 0;
    @Override
    public Integer call() throws Exception {
    System.out.println("执行前" + a );
    a = a.intValue() + 100;
    System.out.println("执行后" + a );
    return a;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask<Integer> task = new FutureT ask<Integer>(new CallableImpl());
    Thread thread = new Thread(task);
    thread.start();
    Integer integer = task.get();
    System.out.println("外部获取返回值:" + integer);
    }
    }
  3. 线程池
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public class ThreadPool implements Runnable {
    @Override
    public void run() {
    System.out.println("Runnable.run()");
    System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10,200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(20));
    Future future;
    for (int i = 0; i < 100; i++) {
    future = executor.submit(new ThreadPool());
    System.out.println("线程返回结果:" + future.get());
    }
    }
    }

总结

  1. 创建线程的方式有4种,有返回值和无返回值
  2. 线程数量小切不需要返回值建议采用实现Runnable接口方式
  3. 需要返回值且线程数小建议采用Callable接口
  4. 线程数较多建议采用线程池,execute提交任务实现无返回值,submit提交任务实现有返回值
  • 标题: Java线程
  • 作者: zlong.w
  • 创建于 : 2020-10-30 15:45:35
  • 更新于 : 2023-09-27 16:24:15
  • 链接: https://zlonx.cn/2020/10/30/Java线程/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
此页目录
Java线程