package com.renrenche.thread;
public class TraditionalThread {
private static int count=0;
public static void main(String[] args){
Thread thread=new Thread(){
@Override
public void run() {
super.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());//this代表run方法所在的对象,在这里就是thread.currentThread(),也就是当前thread,就是此线程。
}
}
};
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("3"+Thread.currentThread().getName());
// System.out.println("4"+this.getName());//this代表run方法所在的对象,在这里就是runnable,不是线程。
}
}
});
thread2.start();
}
}
(2)
Thread thread3=new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable:"+Thread.currentThread().getName());
}
}
}){
@Override
public void run() {
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread:"+Thread.currentThread().getName());
}
}
};
thread3.start();
}
//匿名内部类,相当于子类,此时覆盖了父类的run方法,故运行thread:这个方法。当没有子类的run方法时,才会去父类寻找对应的Runnable
如有疑问,请发邮件:[email protected]
github: https://github.com/wangrui0/