传统线程的创建一般有两种方式,实现Thread类和实现Runnable接口
1.重写Thread Run 方法
Thread thread = new Thread(){
@Override
public void run() {
int count =0;
while (true){
try {
Thread.sleep(1000);
count++;
System.out.println(Thread.currentThread().getName()+":"+count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
2.实现Runnbale接口
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int count =0;
while (true){
try {
Thread.sleep(1000);
count++;
System.out.println(Thread.currentThread().getName()+":"+count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
3.当线程既重写了Thread的run方法,又实现了Runnable的接口,启动时执行的是谁?
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
while (true) {
try {
Thread.sleep(1000);
count++;
System.out.println("runnable:"
+ Thread.currentThread().getName() + ":" + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}) {
@Override
public void run() {
int count = 0;
while (true) {
try {
Thread.sleep(1000);
count++;
System.out.println("Thread:"
+ Thread.currentThread().getName() + ":" + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
显然执行结果是重写Thread的线程,因为java是面向对象语言,这点也不难理解