首先来看一个接口 java.lang.Runnable
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
和一个类 java.lang.Thread
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
他们之间有什么关系呢?我们先来看一下JDK源码(省略无关部分)
public
class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
...
/* What will be run. */
private Runnable target;
...
/**
* Initializes a Thread.
*
* @param g the Thread group
* @param target the object whose run() method gets called
* @param name the name of the new Thread
* @param stackSize the desired stack size for the new thread, or
* zero to indicate that this parameter is to be ignored.
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
...
}
/**
* Allocates a new <code>Thread</code> object. This constructor has
* the same effect as <code>Thread(null, null,</code>
* <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
* a newly generated name. Automatically generated names are of the
* form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
*
* @see #Thread(ThreadGroup, Runnable, String)
*/
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
/**
* Allocates a new <code>Thread</code> object. This constructor has
* the same effect as <code>Thread(null, target,</code>
* <i>gname</i><code>)</code>, where <i>gname</i> is
* a newly generated name. Automatically generated names are of the
* form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
*
* @param target the object whose <code>run</code> method is called.
* @see #Thread(ThreadGroup, Runnable, String)
*/
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
start0();
if (stopBeforeStart) {
stop0(throwableFromStop);
}
}
private native void start0();
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
public void run() {
if (target != null) {
target.run();
}
}
...
}
说明:
这里不讨论JNI或native关键词的用法,暂时只要知道java线程封装了系统本地线程即可;
创建一个线程就是用到上面代码中的两个Thread类的构造方法,
其实我们可以猜想到,其实下面的两个方法都是殊途同归的:
一、从java.lang.Thread继承
定义线程类:
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName() + ": i = " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
说明:
run()方法最好加上注释@Override,它会提示编译器这个方法时覆盖了父类的方法,这样编译器在编译时会检查方法的参数是否和父类一致;
this.getName()就是在Thread类的构造方法中执行的线程名称,默认是Thread+N,我们也可以自己指定更有意义的名称;
Thread.sleep(100)可以让我们演示时看清楚多个线程是在并发执行的,不然可能第一个线程都执行完了,第二个线程才开始执行,看不出是并发执行的;
public class Test {
public static void main(String[] args) {
MyThread threadOne = new MyThread();
MyThread threadTwo = new MyThread();
threadOne.start();
threadTwo.start();
}
}
说明:
这里调用的是线程的start()方法,这个方法才会调用系统接口,创建系统本地线程;
如果直接调用run()方法(不管是父类还是子类的),都只是执行普通的类方法,不会并发执行run()方法中定义的逻辑;
我们在run方法内部打个断点,调试执行一下:
可以看到调用堆栈和之前main方法中不一样了,有一个DestroyJavaVM线程在运行,还有两个我们定义的线程在之前设置的断点出中断。
DestroyJavaVM线程的作用今天先暂时不讲,大家知道这个线程是负责善后工作的就可以了。
二、实现java.lang.Runnable接口
定义线程类:
import java.util.concurrent.atomic.AtomicInteger;
public class MyThread implements Runnable {
private AtomicInteger num;
public MyThread(AtomicInteger num) {
this.num = num;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
for (int i = 0; i < 10; i++) {
System.out.println(threadName + ": i = " + i + ", num = " + num.getAndDecrement());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
说明:
无法调用this.getName()方法,因为它是Thread类中定义的,Runnable接口的方法中没有,要用Thread.currentThread().getName();
定义了一个num,演示实现Runnable接口的线程之间共享数据的一种方式;
引入AtomicInteger,保证线程内部自减操作安全性;
定义测试类:
import java.util.concurrent.atomic.AtomicInteger;
public class Test {
public static void main(String[] args) {
MyThread threadOne = new MyThread(new AtomicInteger(20));
Thread t1 = new Thread(threadOne);
t1.start();
Thread t2 = new Thread(threadOne);
t2.start();
}
}
说明:
这里调用的是Thread类的带参数构造方法,将实现Runnable接口的类的对象当做参数传入;
创建一个MyThread类的对象,创建两个线程,都将这个类的对象作为参数传入,此时threadOne中num就在两个线程中共享,
因为两个线程调用的定义如下,而每个线程内部target都是同一个,达到共享数据的目的。
if (target != null) {
target.run();
}