325 继承Thread类的方式实现多线程
(查看帮助文档-Thread)
【多线程的实现方式】
方式1,继承Thread类
- myThread类继承Thread类
- 在myThread类中,重写run方法
- 创建myThread类的对象
- 启动线程
Q1:为什么要重写run方法?
——因为不是所有代码都要执行,为了区分需要执行的代码,所以重写
Q2:run方法和start方法的区别
——run封装线程执行的代码,直接调用,相当于普通方法的调用,start启动线程,然后由JVM调用此线程的run方法
---------------------------------------------
package e325aso;
public class myThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.print(i);
}
}
}
---------------------------------------------
package e325aso;
public class myThreadDemo325 {
public static void main(String[] args) {
myThread my1 = new myThread();
myThread my2 = new myThread();
my1.run();
my2.run();
// 如果这是多线程程序,则两个run可同时运行
// 运行后,发现是先输出0-99,然后又输出一遍,所以不是多线程的。
// 查看帮助文档可知,Thread中有start方法,导致此线程开始执行,Java虚拟机调用此线程的run方法,
// 由此可知,要用start方法才可以执行线程
//注释掉run方法的调用,使用start方法,再运行一次
// my1.start();
// my2.start();
}
}
/*
0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.
0.0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.1.29.2.30.3.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.4.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.5.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.35.36.37.38.39.40.41.42.43.44.45.46.47.48.49.50.51.52.53.54.55.56.57.58.59.60.61.62.63.64.65.66.67.68.69.70.71.72.73.74.75.76.77.78.79.80.81.82.83.84.85.86.87.88.89.90.91.92.93.94.95.96.97.98.99.
*/