1、新建一个类并继承Thread类
class MyThread extends Thread {
private String title;
public MyThread(String title) {
this.title = title;
}
}
public class TestThread {
public static void main(String[] args) {
}
}
2、覆写Thread类中的run()方法(线程的主体方法)
class MyThread extends Thread {
private String title;
public MyThread(String title) {
this.title = title;
}
public void run() {
for (int x = 0; x < 10; x++) {
System.out.println(this.title + "运行,x =" + x);
}
}
}
public class TestThread {
public static void main(String[] args) {
}
}
3、多线程要执行的功能都应该在run()方法中定义,启动多线程必须使用start()方法,run()方法是顺序执行,start()方法是交替执行,执行顺序不可控,run()方法结果如下图
start()方法结果如下图