一个程序中想要实现线程可以通过继承Thread或者实现Runable接口来实现,两者之间的区别有:
1.继承只能单继承而实现可以多实现。
2.Thread和Runnable是代理模式
Runnable定义线程规范(run()),Thread实现线程作用(start())。
3.Runnable共享数据更方便
例子:
使用继承Thread实现线程时:
public class Test1 extends Thread {
int num;
public static void main(String[] args) {
Test1 thread = new Test1();
thread.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(“mian” + i);
}
}
public static void A() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("test:" + i);
}
}
@Override
public void run() {
A();
}
}
此时我们通过Test1 thread = new Test1();thread.start();来开始线程,我们若要开启多个线程便要new 多个Test1(),此时便会创建多个num值,调用num时就会更加麻烦但是当我们使用实现Runnable接口来实现线程时:
public class Test1 implements Runnable {
int num;
public static void main(String[] args) {
Thread thread = new Thread();
thread.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(“mian” + i);
}
}
public static void A() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("test:" + i);
}
}
@Override
public void run() {
A();
}
}
此时我们要调用多线程则只需要Thread thread = new Thread();thread.start();这时我们使用多线程时,则不会创建对象,num的值也不会增加,使用num也会更加方便。
因为以上几点,所以我们在实际编码中一般使用实现Runnable接口来实现多线程。