Thread 类定义了 start 方法。调用 start 方法后,系统会开启一个新线程进入就绪状态:由 JVM 会自动对线程进行调度,在运行时调用并执行线程的 run 方法。一个线程只能启动一次。
如果自定义线程类继承 Thread 类,直接启动。
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread("ThreadName");
t1.start();
t2.start();
}
}
如果自定义线程类实现 Runnable 接口,则需要借助 Thread 类启动线程。
public class Main {
public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread t1 = new Thread(mythread); // 由系统指定默认线程名 Thread-X
Thread t2 = new Thread(mythread, "ThreadName"); // 开发者自定义线程名
t1.start();
t2.start();
}
}