文件目录:
方法一:
通过继承Thread类来实现创建线程:
package Thread;
public class Thread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("通过继承Thread类创建的线程1" + "--------" + i);
}
}
}
方法二:
通过Runnable接口来实现创建线程:
package Thread;
public class RunnableImpl implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("通过Runnable接口创建的线程2" + "--------" + i);
}
}
}
方法一和方法二的运行:
package Thread;
public class Main {
public static void main(String[] args) {
//方法一的运行
Thread1 thread1 = new Thread1();
thread1.start();
//方法二的运行
RunnableImpl runnable = new RunnableImpl();
Thread thread = new Thread(runnable);
thread.start();
}
}
注意:方法二虽然复杂一点且需要new两个对象,但是相较于方法一,方法二可以继承其他的类(一个类只能继承唯一的类,不能继承多个类)。在一个类需要继承其它类的前提下,则需要用方法二来创建线程,而且Runnable接口降低了线程对象和线程任务的耦合性。
运行图示:
注意:每次运行结果都不一样(多线程,每条线程互不影响)