Java多线程总结(1) — 创建线程的两种方式

本文介绍了Java多线程的基本概念,包括Process和Thread,并详细阐述了创建线程的两种方式:实现Runnable接口和继承Thread类。通过分析优缺点,建议在需要实现多个接口时选择实现Runnable,因为Java不支持多重继承。此外,从Java 8开始,可以使用Lambda表达式简化Runnable的实现。
摘要由CSDN通过智能技术生成

1. 基本概念

1.1 Process

A process is a self contained execution environment and it can be seen as a program or application. However a program itself contains multiple processes inside it. Java runtime environment runs as a single process which contains different classes and programs as processes.

1.2 Thread

Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

1.3 Java Multithreading

Every java application has at least one thread – main thread. Although there are so many other threads running in background like memory management, system management, signal processing etc. But from application point of view – main is the first thread and we can create multiple threads from it.

2. 创建线程的两种方式

2.1 实现 Runnable 接口

/**
 * 实现Runnable接口的方式
 */
public void implementingRunnable() {
    Thread thread = new Thread(new ServiceRunnable("implementingRunnable-->"));
    thread.start();
}

public class ServiceRunnable implements Runnable {

    private String runInfo;

    public ServiceRunnable(String runInfo) {
        this.runInfo = runInfo;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(runInfo + "..Runnable run()...");
            otherMethod();
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public void otherMethod() {
        System.out.println(runInfo + "..otherMethod()...");
    }
}

2.2 继承Thread,覆盖run方法

/**
 * 继承Thread方法
 */
public void extendThread() {
    new ServiceThread().start();
}

public class ServiceThread extends Thread {

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println("..Thread run()...");
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}

3. 问题探讨

  如果两种方式都实现了,即继承了Thread方法,同时传递了Runnable对象,该如何执行?如下代码:

public void bothRunnableThreadTest() {
    new Thread(new Runnable() { // 传递Runnable匿名内部类
        @Override
        public void run() {
            System.out.println("implementingRunnable : run");
        }
    }) {
        @Override
        public void run() { //覆盖父类Thread的run方法
            System.out.println("extendThread : run");
        }
    }.start();
}

  查看Thread的run方法:

    /* What will be run. */
    private Runnable target;

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

  执行run方法先检查如果传递了Runnable,则执行Runnable中的run方法,但由于继承了Thread方法,覆盖了run方法,即父类的run方法不会执行了,所以也就不会执行Runnable中的run方法。上述代码输出:

extendThread : run

4. 两种方式比较

  采用继承Thread类方式:
(1)优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
(2)缺点:因为线程类已经继承了Thread类,所以不能再继承其他的父类。
  采用实现Runnable接口方式:
(1)优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,Runnable的代码可以被多个线程共享(Thread实例),适合于多个线程处理统一资源的情况,从而可以将代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。且符合面向接口而非继承编程的原则。
(2)缺点:编程稍微复杂,如果需要访问当前线程,使用Thread.currentThread()。

Other:If your class provides more functionality rather than just running as Thread, you should implement Runnable interface to provide a way to run it as Thread. If your class only goal is to run as Thread, you can extend Thread class.

Implementing Runnable is preferred because java supports implementing multiple interfaces. If you extend Thread class, you can’t extend any other classes.

Tip: As you have noticed that thread doesn’t return any value but what if we want our thread to do some processing and then return the result to our client program, check our Java Callable Future.

Update: From Java 8 onwards, Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class. For more details, check out Java 8 Lambda Expressions Tutorial.

  转载请注明出处:创建线程的两种方式

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Sunny Mornings

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

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

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

打赏作者

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

抵扣说明:

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

余额充值