创建自定义线程的两种方法
方式1:
自定义线程类,继承Thread类,重写run方法
方式2:
自定义线程类,遵循Runnable接口。实现run方法
使用接口的方式
只能是单继承的,如果继承了Thread类之后,你再继承其他的类的时候就不能继承
MyThead1 extend Thread extends A 最好使用接口的写法!!!!
package com.qfedu.g_thread;
public class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("继承Thread类的线程");
}
}
}
package com.qfedu.g_thread;
public class MyThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("这个是实现Runnable接口的线程");
}
}
}
package com.qfedu.g_thread;
public class Demo1 {
public static void main(String[] args) {
//如何执行线程代码
/*
* 1.创建自定义线程的类对象
* 2.使用start方法进行开启线程(错误的写法是对象.run()!!!!)
* */
MyThread1 myThread1 = new MyThread1();
myThread1.start();
/*
* 1.实现Runable的接口实现rund方法
* 2.创建自定义类对象
* 3.把自定义的类对象当成参数传给Thread类。
* 4.再用对象.tart()
*
* */
Thread thread = new Thread(new MyThread2());
thread.start();
/**/
for (int i = 0; i < 10000; i++) {
System.out.println("这个是主函数线程");
}
}
}