第一种启动线程的方法:
利用thread(通过覆盖thread的run方法)
Thread thread1 = new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1--" + Thread.currentThread().getName());
}
}
};
thread1.start();
第二种启动线程的方法:
利用Runnable,将线程要执行的代码放在Runnable中
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1--" + Thread.currentThread().getName());
}
}
});
thread2.start();
推荐使用Runnable方式来创建线程
1. 避免单继承的限制
2. 将代码封装到了Runnable中,符合面向对象的思想
Thread类内部:
thread的run方法中其实执行的就是runnable对象的run方法
private Runnable target;
public void run() {
if (target != null) {
target.run();
}
}
理解下面的例子:
执行结果:
thread--Thread-0
thread--Thread-0
thread--Thread-0
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable--" + Thread.currentThread().getName());
}
}
}) {
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread--" + Thread.currentThread().getName());
}
};
}.start();
Thread的接收Runnable参数的构造方法中:
init中实现的就是this.target=target;
所以执行的run方法其实还是Runnable执行的run方法
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
而上面的例子的thread覆盖了run方法,也就是不执行target.run(),而是执行自己覆盖后的run方法中的内容。
所以程序的结果是:执行thread的run方法中的内容,而非runnable的run方法中的内容。