创建线程三种方式

1、创建线程三种方式

1.1、继承Thread创建线程

  1. 定义Thread类的子类,并重写该类的run方法,该run方法的方法体就代表了线程要完成的任务。因此把run()方法称为执行体。
  2. 创建Thread子类的实例,即创建了线程对象。
  3. 调用线程对象的start()方法来启动该线程。
public class ThreadTest1 extends Thread {

    @Override
    public void run() {
        for (int i=0; i < 5; i++) {
            System.out.println(getName() + "  " + i);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + "  : " + i);
            if (i == 2) {
                new ThreadTest1().start();
                new ThreadTest1().start();
            }
        }
    }
}

 1.2 通过Runnable接口创建线程

  1. 定义runnable接口的实现类,并重写该接口的run()方法,该run()方法的方法体同样是该线程的线程执行体。
  2. 创建 Runnable实现类的实例,并以此实例作为Thread的target来创建Thread对象,该Thread对象才是真正的线程对象。
  3. 调用线程对象的start()方法来启动该线程。
public class RunnableThreadTest1 implements Runnable {

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 2) {
                RunnableThreadTest1 rtt = new RunnableThreadTest1();
                new Thread(rtt, "新线程1").start();
                new Thread(rtt, "新线程2").start();
            }
        }
    }
}
public class RunnableThreadTest2 {
    
    public static void threadRunCodeStatic() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }

    public void threadRunCode() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }

    public void testStatic() {
        // 重用静态方法中的代码【使用方法引用】
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 2) {
                new Thread(RunnableThreadTest2::threadRunCodeStatic, "线程1").start();
                new Thread(RunnableThreadTest2::threadRunCodeStatic, "线程2").start();
            }
        }
    }

    public void testNoStatic() {
        // 重用非静态方法中的代码【使用方法引用】
        RunnableThreadTest2 temp = new RunnableThreadTest2();
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 2) {
                new Thread(temp::threadRunCode, "线程1").start();
                new Thread(temp::threadRunCode, "线程2").start();
            }
        }
    }

    public void testLambda() {
        // 重用静态方法中的代码【使用方法引用】
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 2) {
                new Thread(() -> {
                    for (int b = 0; b < 5; b++) {
                        System.out.println(Thread.currentThread().getName() + " " + b);
                    }
                },"线程1").start();
                new Thread(() -> {
                    for (int b = 0; b < 5; b++) {
                        System.out.println(Thread.currentThread().getName() + " " + b);
                    }
                },"线程2").start();
            }
        }
    }
}

1.3 通过Callable和Future接口创建线程

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
  1. 创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
  2. 创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。(FutureTask是一个包装器,它通过接受Callable来创建,它同时实现了Future和Runnable接口。)
  3. 使用FutureTask对象作为Thread对象的target创建并启动新线程。
  4. 调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
public class CallableThreadTest implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
        return i;
    }

    public static void main(String[] args) {
        // 创建Callable对象,构建FutureTask
//        CallableThreadTest ctt = new CallableThreadTest();
//        FutureTask<Integer> ft = new FutureTask<>(ctt);

        // 使用Lambda表达式
        FutureTask<Integer> ft = new FutureTask<>(() -> {
            int i = 0;
            for (; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            return i;
        });

        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
            if (i == 2) {
                new Thread(ft, "有返回值的线程").start();
            }
        }
        try {
            System.out.println("子线程的返回值:" + ft.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

}

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

2.1 实现Runnable、Callable接口的方式创建多线程

优势:

  1. 线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。
  2. 在这种方式下,多个线程可以共享同一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU、代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。

劣势:

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

2.2 继承Thread类的方式创建多线程

优势:

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

劣势:

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

2.3 Runnable和Callable的区别

  1. Callable规定(重写)的方法是call(),Runnable规定(重写)的方法是run()。
  2. Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
  3. call方法可以抛出异常,run方法不可以。
  4. 运行Callable任务可以拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值