创建多线程的两种方式,如下
package com.xl.demo;
public class TraditionalThread {
public static void main(String[] args) {
//创建线程方式1
Thread thread = new Thread() {
@Override
public void run() {// 改写父类的run方法
while (true) {
try {
Thread.sleep(5000);
System.out.println("th 1"
+ Thread.currentThread().getName());
System.out.println("th 2" + this.getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
thread.start();
//创建线程方式2 使用Run那边了接口
Thread thread2 = new Thread(new Runnable(){
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
System.out.println("th 1"
+ Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread2.start();
/**
* 下面的程序将执行Thread子类的run方法,只有在没有重写Thread的run方法时,才会执行Runable中的run方法
*/
new Thread(new Runnable(){
public void run() {
while (true) {
try {
Thread.sleep(5000);
System.out.println("Runnable run method "
+ Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}){
public void run() {
while (true) {
try {
Thread.sleep(5000);
System.out.println("Thread run method "
+ Thread.currentThread().getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}