一.方式一—–继承Thread类的方式开启
1.步骤:
1)定义类继承Thread类
2)重写Thread类中的run方法,用来指定我们线程的任务
3)创建线程对象
4)调用线程的start方法,启动线程
2.注意点:
- 1.启动线程不是调用run方法,如果调用的是run方法,那么就和普通对象调方法是一样的,没有区别
- 启动线程调用的start方法
- 2.线程不可以多次启动
3.代码示例
定义线程
// 方式一: 继承Thread类的方式开启
// 1.定义类继承Thread类
class MyThread extends Thread {
private int tickets = 100;
// 2.重写Thread类中的run方法,用来指定我们线程的任务
public void run() {
// run方法如何编写? ==> main方法怎么写,run方法就怎么写.
// 这里我们完全可以理解为我们自己定义的main方法
for (int i = 1; i <= 100; i++) {
System.out.println(this.getName() + ":" + i);
}
}
}
public class ThreadDemo02 {
public static void main(String[] args) {
// 3.创建线程对象
Thread t1 = new MyThread(); // t1维护了100张票
Thread t2 = new MyThread(); // t2维护了100张票
Thread t3 = new MyThread(); // t3维护了100张票
t1.start();
t2.start();
t3.start();
}
}
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/2337.html原文链接:https://javaforall.net