线程第一种定义方式:
1.继承Thread类 2.在子类中重写run()方法 3.调用start()方法启动线程(自带方法不是定义方法)
public class Test {
class Runner extends Thread{
@Override
public void run() {
Integer speed = new Random().nextInt(10);
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("第"+i+"秒"+this.getName()+"已跑到"+(i*speed)+"米,速度"+speed);
}
}
}
public void start(){
Runner runner = new Runner();
Thread thread = new Thread(runner);
thread.start();
}
public static void main(String[] args) {
new Test().start();
}
}
线程第二种定义方式:
通过Runnable接口实现
public class Test { class Runner implements Runnable{ @Override public void run() { Integer speed = new Random().nextInt(10); for (int i = 1; i <= 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("第"+i+"秒"+Thread.currentThread().getName()+"已跑到"+(i*speed)+"米,速度"+speed);//与第一种实现方式相比,此处代码差别最大 } } } public void start(){ Runner runner = new Runner(); Thread thread = new Thread(runner); thread.setName("参赛者A"); thread.start(); } public static void main(String[] args) { new Test().start(); } }