// 线程的理解,传统上有两种方式,一种是直接new Thread 大家可以想象,为什么掉start方法就
// 可以运行run方法呢?大家可以看Thread的源代码
/**
* 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);
}
}
方法说的很明白,Java 虚拟机调用该线程的 run 方法。
结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。
多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。
eg:
// Thread thread = new Thread(){
// @Override
// public void run() {
// while(true){
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
// };
// thread.start();
//
// 这是第二种方式,可以看Thread.java的第二种构造方式
/**
* 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();
}
}
可以看出当targer不等于null的时候,我们执行target的run方法。这个target是构造时候传入
进来的runnable对象。可以,下面是线程的第二种方式
// Thread thread2 = new Thread(new Runnable(){
// @Override
// public void run() {
// while(true){
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// }
// });
// thread2.start();
思考下面的代码,是打印出什么呢?是runnable还是thread?答案是肯定的,答应thread。
因为此时new thread()代表是thread的子类,而且我们覆盖了父类的run方法,所以,当执行
start方法的时候,我们去子类寻找,如果找到了run,就不去父类找了。当子类不存在的时候,
然后去父类里面判断target是否为空,即runnable的run方法、
说道这里,大家思考下,为什么我们写代码基本都是用的第二种线程的书写方式呢?他有什么好处?
其实,好处谈不上,只是说,第二种线程的方法,更加能体现java的面向对象的思想。构造方法里面
传入的参数也是对象,彼此的结构封装的很好。
new Thread(
new Runnable(){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable");
}
}
}
){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread ");
}
}
}.start();
}