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());
System.out.println("2:"+this.getName());
}
}
};
thread.start();
第二种方法
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());
}
}
});
thread2.start();
创建子类并在里面写方法
new Thread(
/*这里的方法不运行*/
new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("**********:"+Thread.currentThread().getName());
}
}
}){
/*运行这里的方法*/
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("8888888888:"+Thread.currentThread().getName());
}
}
}.start();
本文通过示例展示了两种创建Java线程的方法:一种是继承Thread类并重写run方法;另一种是实现Runnable接口并通过Thread类启动。此外,还提供了一个通过创建Thread子类并重写run方法的例子。

被折叠的 条评论
为什么被折叠?



