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();
}
But this is a common method call, and there is no new thread, so it loses the meaning of the thread itself.
二、实现Runnable接口
1、定义一个线程类来实现Runnable接口,并重写接口的run()方法,该方法仍然包含指定要执行的程序。
2、创建一个Runnable实现类实例,将其作为目标参数传递,并创建一个Thread类实例。3、调用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实现类的实例作为参数目标传入时,它被分配给当前线程类的目标,而在run()中执行的程序是分配给该目标的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();
}
}
三、使用Callable和Future创建线程
使用Callable创建线程类似于使用Runnable接口创建线程。区别在于Callable接口提供call()方法作为线程执行器,而Runnable接口提供run()方法。同时,call()方法可以具有返回值,并且需要FutureTask类来包装Callable对象。
public interface Callable {
V call() throws Exception;
}
步骤:
1、创建Callable接口的实现类,实现call() 方法
2、创建Callable实现类实例,通过FutureTask类来包装Callable对象,该对象封装了Callable对象的call()方法的返回值。
3、将创建的FutureTask对象作为target参数传入,创建Thread线程实例并启动新线程。4、调用FutureTask对象的get方法获取返回值。
执行main方法后,程序输出如下结果:
task 返回值为:1
注意这个任务。get()返回call()方法的结果。那么它在内部是如何工作的呢?首先打开FutureTask的构造方法,可以看到Callable对象作为参数传递给当前实例的Callable成员。
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
同时,将成员变量状态设置为NEW。当任务启动时,它的run方法执行Callable的call()方法。
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable 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()的返回结果被分配给结果,然后当任务执行时。调用get()方法,获得outcom的值。因此,返回结果是逻辑的。
正如您所看到的,源代码的运行逻辑仍然相对清晰,代码相对容易理解,所以我建议读者有时间查看更多Java的底层源代码,这可以帮助我们理解函数是如何深入实现的。
三种方式的对比
我们已经完成了创建线程的所有三种方法,然后我们将讨论它们的比较。
从实现方式上看,使用Runnable接口和Callable接口的方式基本相同,只有Callable实现的方法体才有返回值,而继承Thread类的方法则使用继承方法,所以实际上可以将这三种方法分为两类进行分析。
1、使用继承Thread类的方式:
优点:编码简单,并且当需要获取当前线程时,可以直接使用它
缺点:因为Java支持单继承,继承继承线程后不能继承其他父类
2、使用Runnable接口和Callable接口的方式: