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

来源:互联网 发布:日语网络教育 编辑:程序博客网 时间:2024/06/05 20:21

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 0
原创粉丝点击