java中线程

public interface Runnable {
    public abstract void run();
}

public class Thread implements Runnable {
private Runnable target; 
public Thread() {
     create(null, null, null, 0);
    }

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

public synchronized void start() {
        start0();}
private native void start0();
@Override
public void run() {
       if (target != null) {
           target.run();
        }
    }
}

不需要返回结果时,可以使用继承Thread类和实现Runnable接口来创建线程

以上为部分源码当继承Thread类创建线程时,覆写run方法其实还是在实现Runnable接口中的抽象方法run,new对象时调用的是Thread类中的无参构造器,调用其start方法执行

run方法体;实现Runnable接口来创建线程时,实现其抽象方法run,执行run方法只能使用Thread类中的start方法(native),所以newThread类对象时调用的是其有参构造器,将实现的Runnable接口赋值给This.Runnable,使用Thread类中的start方法执行实现Runnable接口中覆写的run方法

所以两种方法都是实现实现Runnable的抽象方法run,使用Thread类中的start方法执行其run方法体

 

当需要线程返回执行结果时,就要使用Callable接口

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;
}

与runable接口类似callable接口也只有一个方法call,返回结果使用泛型

如图java 5提供future接口来代表Callable接口里call方法的返回值,并为future接口提供了一个futureTask实现类,该实现类实现了Future接口,并实现了Runnable接口,

可以作为Thread类的Target以下为FutureTask的两个构造方法

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

为了更好的使用线程,下面学习一下线程池方面的知识

线程池在系统启动时即创建大量空闲的线程,程序将一个runnable对象或callable对象传给线程池,线程池就启动一个线程来执行它们的run或call方法,当run或call方法执行

结束后,该线程并不会死亡,而是再次返回到线程池中成为空闲状态,等待执行下一个Runnable对象或callable对象的run或call方法

java5开始新增一个Executors工厂类来产生线程池,ExecutorService代表尽快执行线程的线程池(只要线程池有空闲线程,就立即执行线程任务)程序只要将一个Runnable对象

或callable对象提交给线程池,该线程池就会尽快执行该任务

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

一般情况下使用第一个和第三个

使用举例:http://www.cnblogs.com/ruiati/p/6133174.html

 

 

参考 http://www.cnblogs.com/cuimiemie/p/6445154.html

http://www.cnblogs.com/ruiati/p/6133174.html

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值