创建线程的两种方法:
package com.thread;
public class TestThread1 {
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("1"+Thread.currentThread().getName());
System.out.println("2"+this.getName());
}
}
};
thread.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("1"+Thread.currentThread().getName());
}
}
});
thread2.start();
}
}
常用的是调用Runable方法来创建,原因是这样更能体现面向对象思想。
如果执行以下代码
new Thread(
new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread"+Thread.currentThread().getName());
}
}
}
){
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread"+Thread.currentThread().getName());
}
};
}.start();
运行结果:
threadThread-2
threadThread-2
threadThread-2