1.使用Thread子类的方法
public class A extends Thread{ //注意此处 ,Thread的子类
public void run() {
for(int i=0;i<10;i++)
System.out.println("A");
}
}
public class Main {
public static void main(String[] args) {
A a = new A(); //直接实例化一个对象。
a.start();
for(int i = 0; i<10;i++) {
System.out.println("B");
}
}
}
2.使用Runnable接口
public class B implements Runnable{ //!!!!!!此处类B实现了接口Runnable
public void run() {
for(int i=0;i<10;i++)
System.out.println("B");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
Thread a = new Thread(b);
//Thread(Runnable target)构造方法创建的线程,轮到它使用cpu资源时,目标对象会自动调用接口中的run()方法
a.start();
for(int i = 0; i<10;i++) {
System.out.println("A");
}
}
}