创建线程的两种方式
1.在Thread子类覆盖的run方法中编写运行代码
Thread thread1 = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1 : " + Thread.currentThread().getName());
System.out.println("2 : " + this.getName());
}
}
};
thread1.start();
2.在传递给Thread对象的Runnable对象的run方法中编写代码
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());
// 这里为什么不能使用 this.getName();??
// 首先,这里如果使用 this 的话,代表的是一个 Runnable 接口的实现对象
// 而且上述只是实现了其run方法,并没有任何与getName方法有关的定义,如果直接调用自然会报错
// System.out.println("2' : " + this.getName());
}
}
// 加入再下面扩展了getName 方法的话,那么就可以简单的实现可以调用了
public String getName() {
return Thread.currentThread.getNa