创建线程的方式

方式1:继承Java.lang.Thread类,并覆盖run() 方法。优势:编写简单;劣势:无法继承其它父类

public class ThreadDemo1 {

public static void main(String args[]) {

MyThread1 t = new MyThread1();

t.start();

while (true) {

System.out.println("兔子领先了,别骄傲");

}

}

}

class MyThread1 extends Thread {

public void run() {

while (true) {

System.out.println("乌龟领先了,加油");

}

}

}

方式2:实现Java.lang.Runnable接口,并实现run()方法。优势:可继承其它类,多线程可共享同一个Thread对象;劣势:编程方式稍微复杂,如需访问当前线程,需调用Thread.currentThread()方法

public class ThreadDemo2 {

public static void main(String args[]) {

MyThread2 mt = new MyThread2();

Thread t = new Thread(mt);

t.start();

while (true) {

System.out.println("兔子领先了,加油");

}

}

}

class MyThread2 implements Runnable {

public void run() {

while (true) {

System.out.println("乌龟超过了,再接再厉");

}

}

}

posted on 2019-07-29 19:57  袁音元音i  阅读(105)  评论(0)    收藏  举报