使用Thread创建线程通常使用的方法是:Thread(Runnable target)。该构造方法中的参数是一个Runnable类型的接口,因此在创建线程对象时必须向构造方法的参数传递一个实现Runnable接口类型的实例。
代码展示如下所示:
public class Test06 { public static void main(String[] args) { // TODO Auto-generated method stub Thread speakElephant; Thread speakCar; ElephantTarget elephant; CarTarget car; elephant = new ElephantTarget(); car = new CarTarget(); speakElephant = new Thread(elephant); speakCar = new Thread(car); speakElephant.start(); speakCar.start(); for(int i = 1; i <= 10; i++) { System.out.print("主人" + i + " "); } } }
CarTarget.java
public class CarTarget implements Runnable { @Override public void run() { // TODO Auto-generated method stub for(int i = 1; i <= 10; i++) { System.out.print("轿车" + i + " "); } } }
ElephantTarget.java
public class ElephantTarget implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for(int i = 1; i <= 10; i++) { System.out.print("大象" + i + " "); } } }