一.如何创建线程
1.实现java.lang.Runnable 接口
public interface Runnable{
public abstract void run();
}
2.继承java.lang.Thread 类
源码:
public class Thread extends Object implements Runnable{
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
public void run() {
if (target != null)
target.run();
}
}
可以看出,Thread类实现了Runnable接口,并实现了run()方法。
当用一个Runnable对象作为Thread类参数创建新的线程时,执行的是target.run(),即调用实现Runnable接 口类中重写的run()方法。
两种方法的例子:
public class TwoMethod {
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
while(true){
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("第一个方式........" + Thread.currentThread().getName());
}
}
};
thread.start();
Thread thread2 = new Thread(new Runnable(){
public void run(){
while(true) {
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二种方式........." + Thread.currentThread().getName());
}
}
});
thread2.start();
//new Thread(){}.start();
//new Thread(new Runnable(){}).start()
new Thread(new Runnable(){
public void run() {
while(true) {
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Runnable~~~~" + Thread.currentThread().getName());
}
}
}){
public void run() { //Thread类继承Runnable接口,并在匿名实例中实现了的run方法, 覆盖了 实现 Runnable接口的匿名类中的run方法
while(true) {
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread~~~~" + Thread.currentThread().getName());
}
}
}.start();
}
}
关于两种创建线程方法的比较:
我们知道Java不支持类的多继承,但允许实现多个接口,如果继承了Thread类,就不能再继承其他的父类。
而使用Runnable方式可以多个线程共享同一个目标对象,处理同一份资源,更能体现出面向对象的思想。