/**
* 多线程的创建,方式一:继承Thread类
* 1、创建一个继承于Thread类的子类
* 2、重写thread类的run()方法 -->将此线程执行的操作声明在run()中
* 3、创建Thread类的子类对象
* 4、通过子类调用start()
*
* 比较创建线程的两种方式:
* 开发中:优先选择;实现Runnable接口的方式
* 原因:1、实现的方式没有单继承性的局限性
* 2、实现的方式更适合来处理多个线程又共享数据的情况
*
* 联系: public class Thread implements Runnable
* 相同点:两种方式都要重写run(),将线程执行的操作声明在run()中
*
* @author dqp
* @create 2021-12-12 20:29
*/
//1、创建一个继承于Thread类的子类
class Mythread extends Thread{
//2、重写thread类的run()方法 -->将此线程执行的操作声明在run()中
@Override
public void run() {
for (int i = 0; i <100 ; i++) {
if(i%2 == 0){
System.out.println(i);
}
}
}
}
public class MyThreadTest {
public static void main(String[] args) {
//3、创建Thread类的子类对象
Mythread mythread = new Mythread();
//4、通过子类调用start():1、启动当前线程。 2、调用当前线程的run()
mythread.start();
//问题一:我们不能通过直接调用run()的方式启动线程
//t1.run();
//问题二:再启动一个线程,遍历100以内的偶数,不可以还让已经start()的线程去执行,否则会报IllegalThreadStateException
//t1.start()
//我们需要重新创建一个线程对象
Mythread t1 = new Mythread();
t1.start();
for (int i = 0; i <100 ; i++) {
if(i %2 == 0){
System.out.println(i+"****************main()*************");
}
}
}
}
Java多线程创建方式4种:方式一
最新推荐文章于 2023-04-26 18:55:46 发布