虽然可以通过Thread类的继承来实现多线程的定义,但是在Java程序里面对于继承永远都是存在单继承局限的,所以在Java里面又提供有第二种多线程的主体定义结构形式:实现java.lang.Runnable接口,此接口定义如下:
@FunctionalInterface
public interface Runnable{
public void run();
}
范例:通过Runnable实现多线程的主体类
由于只是实现了Runnable接口对象,所以此时线程主题类上就不再又单继承局限了,那么这样的设计才是一个标准型的设计。
class MyThread implements Runnable{ // 线程的主体类
private String title;
public MyThread(String title) {
this.title = title;
}
@Override
public void run() { // 多线程要执行的功能应该在run()方法中进行定义
for(int i = 0; i < 3; i++) {
System.out.println(this.title + "运行:= " + i);
}
}
}
public class Main {
public static void main(String[] args) {
// new MyThread("线程A").start();
// new MyThread("线程B").start();
// new MyThread("线程C").start();
Thread threadA = new Thread(new MyThread("线程对象A"));
Thread threadB = new Thread(new MyThread("线程对象B"));
Thread threadC = new Thread(new MyThread("线程对象C"));
threadA.start();
threadB.start();
threadC.start();
}
}
注意:没有继承Thread类不能使用start()方法,但是Thread类的构造函数允许接受Runnable的对象,所以实现Runnable的子类对象也可以被Thread类接收
从JDK1.8开始,Runnable接口使用了函数式的接口定义,所以也可以直接利用Lambda表达式进行线程类的实现。
范例:利用Lambda实现多线程的定义
public class Main {
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
String title = "线程对象-" + i;
Runnable run = ()->{
for(int j = 0; j < 5; j++) {
System.out.println(title + "运行, j = " + j);
}
};
new Thread(run).start();
}
// 形式二
// for(int i = 0; i < 3; i++) {
// String title = "线程对象-" + i;
// new Thread ( ()->{
// for(int j = 0; j < 5; j++) {
// System.out.println(title + "运行, j = " + j);
// }
// }).start();
// }
}
}
Java中对于多线程的实现,优先考虑的就是Runnable接口实现,并且永恒都是通过Thread类启动多线程