(1)继承Thread,重写run()方法
public class MyThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println(this.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); //线程启动的正确方式
}
}
输出结果:
Thread-0
Thread-0
Thread-0
...
另外,要明白启动线程的是start()方法而不是run()方法,如果用run()方法,那么他就是一个普通的方法执行了。
(2)实现Runable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("123");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable, "t1");
thread.start();
}
}