Java并发编程:Java建立线程的三种方式

引言

在平常开发工做中,多线程开发能够说是必备技能,好的程序员是必定要对线程这块有深刻了解的,我是Java程序员,而且Java语言自己对于线程开发的支持是很是成熟的,因此今天咱们就来入个门,学一下Java怎么建立线程。程序员

建立线程的三种方式

Java建立线程主要有三种方式:bash

一、继承Thread类多线程

二、实现Runnable接口ide

三、使用Callable和Future建立线程ui

下面分别讨论这三种方法的实现方式,以及它们之间的对比。this

1、继承Thread类

步骤:编码

一、建立一个线程子类继承Thread类spa

二、重写run() 方法,把须要线程执行的程序放入run方法,线程启动后方法里的程序就会运行线程

二、建立该类的实例,并调用对象的start()方法启动线程code

示例代码以下:

public class ThreadDemo extends Thread{
    @Override
    public void run() {
        super.run();
        System.out.println("须要运行的程序。。。。。。。。");
    }

    public static void main(String[] args) {
        Thread thread = new ThreadDemo();
        thread.start();
    }
}
复制代码

当运行main方法后,程序就会执行run()方法里面的内容,执行完以后,线程也就随之消亡,为何必定要重写run()方法呢?

点击方法的源码后,发现Thread的run()方法其实什么都没有作

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

public abstract void run();
复制代码

若是run()里没有须要运行的程序,那么线程启动后就直接消亡了。想让线程作点什么就必须重写run()方法。同时,还须要注意的是,线程启动须要调用start()方法,但直接调用run() 方法也能编译经过,也能正常运行:

public static void main(String[] args) {
    Thread thread = new ThreadDemo();
    thread.run();
}
复制代码

只是这样是普通的方法调用,并无新起一个线程,也就失去了线程自己的意义。

2、实现Runnable接口

一、定义一个线程类实现Runnable接口,并重写该接口的run()方法,方法中依然是包含指定执行的程序。

二、建立一个Runnable实现类实例,将其做为target参数传入,并建立Thread类实例。

三、调用Thread类实例的start()方法启动线程。

public class RunnableDemo implements Runnable{
    @Override
    public void run() {
        System.out.println("我是Runnable接口......");
    }
    public static void main(String[] args) {

        RunnableDemo demo = new RunnableDemo();
        Thread thread = new Thread(demo);
        thread.start();
    }
}
复制代码

这是基于接口的方式,比起继承Thread的方式要灵活不少,但须要多建立一个线程对象,打开源码能够发现,当把Runnable实现类的实例做为参数target传入后,赋值给当前线程类的target,而run()里执行的程序就是赋值进去的target的run()方法。

public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc) {
                      
        ...........这里省略部分源码..........
        
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }
    
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
复制代码

3、使用Callable和Future建立线程

使用Callable建立线程和Runnable接口方式建立线程比较类似,不一样的是,Callable接口提供了一个call() 方法做为线程执行体,而Runnable接口提供的是run()方法,同时,call()方法能够有返回值,并且须要用FutureTask类来包装Callable对象。

public interface Callable<V> {
    
    V call() throws Exception;
}
复制代码

步骤:

一、建立Callable接口的实现类,实现call() 方法

二、建立Callable实现类实例,经过FutureTask类来包装Callable对象,该对象封装了Callable对象的call()方法的返回值。

三、将建立的FutureTask对象做为target参数传入,建立Thread线程实例并启动新线程。

四、调用FutureTask对象的get方法获取返回值。

public class CallableDemo implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int i = 1;
        return i;
    }

    public static void main(String[] args) {
        CallableDemo demo = new CallableDemo();
        FutureTask<Integer> task = new FutureTask<Integer>(demo);

        new Thread(task).start();
        try {

            System.out.println("task 返回值为:" + task.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
复制代码

执行main方法后,程序输出以下结果:

task 返回值为:1
复制代码

说明,task.get()确实返回了call() 方法的结果。那么其内部是怎么实现的呢。先打开FutureTask的构造方法,能够看到其内部是将Callable对象做为参数传递给当前实例的Callable成员,

public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;       // ensure visibility of callable
}

复制代码

同时,将成员变量state置为NEW,当启动task后,其run方法就会执行Callable的call()方法,

public void run() {
    if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
            	//把call()的返回结果复制给result
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran)
            	//将结果设置给其余变量
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}
protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        	//把传过来的值赋值给outcome成员
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
复制代码

run()方法中通过一系列的程序运行后,把call()的返回结果赋值给了outcome,而后当调用task.get()方法里获取的就是outcome的值了,这样一来,也就瓜熟蒂落的获得了返回结果。

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}
private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
        	//返回outcome的值
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }
复制代码

能够看出,源码的运行逻辑仍是比较清晰的,代码也比较容易理解,因此,我比较建议读者们有空能够多看看Java底层的源码,这样能帮助咱们深刻的理解功能是怎么实现的。

三种方式的对比

好了,建立线程的三种方式实例都说完了,接下来讲下他们的对比。

从实现方式来讲,使用Runnable接口和Callable接口的方式基本相同,区分的只是Callable实现的方法体能够有返回值,而继承Thread类是使用继承方式,因此,其实三种方法归为两类来分析便可。

一、使用继承Thread类的方式:

  • 优点:编码简单,而且,当须要获取当前线程,能够直接用this
  • 劣势:因为Java支持单继承,因此继承Thread后就不能继承其余父类

二、使用Runnable接口和Callable接口的方式:

  • 优点:

比较灵活,线程只是实现接口,还能够继承其余父类。

这种方式下,多个线程能够共享一个target对象,很是适合多线程处理同一份资源的情形。

Callable接口的方式还能获取返回值。

  • 劣势:

编码稍微复杂了点,须要建立更多对象。

若是想访问当前线程,须要用Thread.currentThread()方法。

总的来讲,两种分类都有各自的优劣势,但其实后者的劣势相对优点来讲不值一提,通常状况下,仍是建议直接用接口的方式来建立线程,毕竟单一继承的劣势仍是比较大的。

相关文章
相关标签/搜索