方法一:通过继承Thread方法:(在Thread子类覆盖的run方法编写运行代码)
public class ThreadTest1 {
public static void main(String[] args) {
Thread thread1=new Thread(){
public void run(){
while(true){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1:"+Thread.currentThread().getName());
}
}
};
thread1.start();
}
方法二:通过实行Runnable接口(在传递给Thread对象的Runnable对象的run方法中编写代码)
public class ThreadTest1 {
public static void main(String[] args) {
Thread thread2=new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2:"+Thread.currentThread().getName());
}
}
});
thread2.start();
}
}
总结:从源码可以看到,这两种方法都是在调用Thread对象的run方法,如果Thread类的run方法没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run方法。
问题:如果Thread子类覆盖的run方法中编写了运行代码,也为Thread子类对象传递了一个Runnable对象,那么,线程运行的执行代码是子类的run方法代码,还是Runnable对象的run方法的代码?
public class ThreadTest1 {
public static void main(String[] args) {
//new Thread(new Runnable.run){run}.start
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("runnable:"+Thread.currentThread().getName());
}
}
}){
public void run(){
while(true){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread:"+Thread.currentThread().getName());
}
}
}.start();
}
}
上述代码结构为:new Thread(new Runnable.run){run}.start();这可根据匿名内部类的对象的构造方法来调用父类的非默认构造方法。运行结果为:
thread:Thread-0
thread:Thread-0
thread:Thread-0
....
thread:Thread-0