Java语言已经内置了多线程支持,所有实现Runnable接口的类都可被启动一个新线程。
新线程会执行该实例的run()方法,当run()方法执行完毕后,线程就结束了。一旦一个线程执行完毕,这个实例就不能再重新启动,只能重新生成一个新实例,再启动一个新线程。
Thread类是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。
Thread t = new Thread();
t.start();
start()启动一个新线程,并执行run()方法。Thread类默认的run()方法什么也不做就退出了。
注意:直接调用run()方法并不会启动一个新线程,它和调用一个普通的Java方法没有什么区别。有两个方法可以实现自己的线程。
ONE
扩展(继承)Thread类,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。
public class MyThread extends Thread {
public run() {
System.out.println("MyThread.run()");
}
}
在合适的地方启动线程即可。
new MyThread().start();
TWO
如果类已经extends另一个类,就无法直接继承Thread类,那么,必须实现一个Runnable接口。
public class MyThread extends OtherClass implements Runnable {
public run() {
System.out.println("MyThread.run()");
}
}
为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例。
MyThread myt = new MyThread();
Thread t = new Thread(myt);
t.start();
事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run()。
Thread类的部分源代码如下:
/**
* Starts the new Thread of execution. The <code>run()</code> method of
* the receiver will be called by the receiver Thread itself (and not the
* Thread calling <code>start()</code>).
*
* @throws IllegalThreadStateException if the Thread has been started before
*
* @see Thread#run
*/
public synchronized void start() {
if (hasBeenStarted) {
throw new IllegalThreadStateException("Thread already started."); // TODO Externalize?
}
hasBeenStarted = true;
VMThread.create(this, stackSize);
}
/**
* Calls the <code>run()</code> method of the Runnable object the receiver
* holds. If no Runnable is set, does nothing.
*
* @see Thread#start
*/
public void run() {
if (target != null) {
target.run();
}
}