Java语言是一种单继承,多实现的面向对象的语言
自定义线程的的方式:
方式1:
1. 自定义一个类,继承Thread类
2. 重写Thread类里边的run方法,把线程的功能代码放入到run方法中
3. 创建自定义线程类对象
4. 开启线程,使用start方法
弊端:
因为Java是一个单继承的语言,一旦某一个类继承了Thread类,就无法继承其他类。
或者说一个类继承了其他类,也就无法继承Thread类
方式2:【推荐】
实现Runnable接口实现自定义线程类
1. 自定义一个类,实现Runnable接口
2. 实现Runnable接口中唯一要实现的run方法,把线程的功能代码写到run方法中
3. 创建Thread类对象,把实现Runnable接口的自定义类对象,作为参数传入到Thread构造方法中
代码
class TestRunnable implements Runnable {
// 实现自定义线程类,实现Runnable中的run方法
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("当前线程为:" + Thread.currentThread());
}
}
}
public class Demo {
public static void main(String[] args) {
// 创建Thread类,调用Thread构造方法中,需要传入Runnable接口实现类对象的方法
Thread t1 = new Thread(new TestRunnable());
Thread t2 = new Thread(new TestRunnable());
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("匿名内部类的匿名对象作为方法的参数," + Thread.currentThread());
}
}
});
t1.start();
t2.start();
t3.start();
}
}