一在子类 Thread中创建线程并覆盖
Thread thread=new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
System.out.println(this.getName());
}
}
};
thread.start();
实现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(Thread.currentThread().getName());
//不能用这种方法
//System.out.println(this.getName());
}
}
}
);
同时实现子类和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(Thread.currentThread().getName());
//不能用这种方法
//System.out.println(this.getName());
}
}
}
) {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
System.out.println(this.getName());
}
}
};
会执行被覆盖的run方法,而不会执行Runnable方法,因为 子类将父类的run方法覆盖了,所以run方法不会再去找Runnable里面的run方法