Java编程--多线程(继承Thread类和实现Runnable接口)
一. 通过继承Thread类
//线程操作主类
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int x = 0; x < 20; x++) {
System.out.println(this.name + "-->" + x);
}
}
}
// 主类
public class ThreadTest1 {
public static void main(String[] args) {
MyThread mt1 = new MyThread("Thread1");
MyThread mt2 = new MyThread("Thread2");
MyThread mt3 = new MyThread("Thread3");
//多线程启动的唯一方法就是Thread类中的start()方法
mt1.start();
mt2.start();
mt3.start();
}
}
运行结果:此时每一个线程对象交替执行。
抛出: