创建线程有两种方法,一种是
继承Thread类创建线程类,而另外一种是实现Runnable接口创建线程类。那么这两种方法本质上有什么区别呢?我们平时更倾向于哪种呢?下面我们就来讨论下着两种方法的优势与劣势;
1).继承Thread类创建线程类 实现Runnable接口创建线程类
public class Thread1 extends Thread{
@Override
public void run() {
while(true){
System.out.println("1" + Thread1.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread1 th = new Thread1();
th.start();
}
}
2).实现Runnable接口创建线程类
public class Thread2 implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("线程"+ Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread2 th2 = new Thread2();
Thread th1 = new Thread(th2);
th1.start();
}
}
那么这两种方法有什么区别呢?
先来说说第一种吧:
采用继承Thead类实现多线程:
优势:编写简单,如果需要访问当前线程,只需使用this即可,无需使用Thead.currentThread()方法。
劣势:因为这种线程类已经继承了Thead类,所以不能再继承其它类。
第二种方法:
采用实现Runable接口的多线程:
优势:线程类只是实现了Runable接口,因此还可以继承其他类;
在这种情况下,可以使多个线程共享一个target对象,所以非常适合多个线程用来处理同一份资源的情况,从而可以将cpu、代码和数据分开,形成清晰的模型,较好的体现面向对象思想。
劣势:编程略有些复杂,如果要访问当前线程必须使用Thread.currentThread方法。