创建线程的三种方式
第一种,用Thread子类创建
Thread thread = new Thread(){ @Override public void run() { while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("1---->" + Thread.currentThread().getName()); } } }; thread.start();
第二种:用Runnable接口实现
/**
* 第二种通过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("2---->" +Thread.currentThread().getName());
}
}
});
thread2.start();
第三种:Runnable和Thread类 并存
/**
* 第三種 通過Thread子類創建和通過Runnable创建
* 两种方式并存的时候系统会调用实现子类的run的那个线程,会把实现接口的那个线程覆盖,和面向对象的重写思路一样。
*/
new Thread(new Runnable(){
//Thread子类创建
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable接口创建---->" +Thread.currentThread().getName());
}
}
}){
//Runnable接口创建
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread子类创建---->" +Thread.currentThread().getName());
}
}
}.start();

浙公网安备 33010602011771号