线程的两种创建方式
第一种,继承 Thread:
public class TestThread{
public static void main(String[] args){
MyThread1 t1 = new MyThread1();
MyThread2 t2 = new MyThread2();
t1.start();
t2.start();
}
}
class MyThread1 extends Thread{
@Override
public void run(){
for(int i = 1; i <= 50; i++)
System.out.println("MyThread1: " + i);
}
}
class MyThread2 extends Thread{
@Override
public void run(){
for(int i = 1; i <= 50; i++)
System.out.println("MyThread2: " + i);
}
}
运行效果:
第二种,通过 Runnable 接口(推荐
):
public class TestThread2{
public static void main(String[] args){
MyRunnable task = new MyRunnable();
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run(){
for(int i = 1; i <= 50; i++)
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
运行效果: