注:多线程学习主要参照张孝祥的视频教程,本文的将学习的内容记录下来,以便以后作为笔记回顾!
1.创建线程的两种传统方式:
public class TreadTest {
public static void main(String[] args) {
//第一种方式,覆盖父类的run方法
Thread t=new Thread(){
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("0"+Thread.currentThread().getName());
//System.out.println("1"+this.getName());
}
};
};
t.start();
//第二种方式,new runable对象
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2"+Thread.currentThread().getName());
}
}
});
t2.start();
2.问题
如果在Thread子类覆盖的run方法中编写了运行代码,也为Thread子类对象传递了一个Runnable对象,那么,线程运行时的执行代码是子类的run方法的代码?还是Runnable对象的run方法的代码?
public class TreadTest {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("3"+Thread.currentThread().getName());
}
}
}){
//执行的是下面的方法,也就是该类覆盖的父类方法run()
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("4"+Thread.currentThread().getName());
}
}}.start();;
}
}
上面的代码会执行下面的重写run()方法的代码。
总结:查看Thread类的run()方法的源代码,可以看到其实这两种方式都是在调用Thread对象的run方法,如果Thread类的run方法没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run方法。