Java中Runnable和Thread的区别

在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;

Thread:

实现方式:继承Thread类,重写里面的run方法,用start方法启动线程

(但是一个类只能继承一个父类,这是此方法的局限。)

public class Main {

public static void main(String[] args) {

//测试Runnable
MyThread1 t1 = new MyThread1();
new Thread(t1).start();//同一个t1,如果在Thread中就不行,会报错
new Thread(t1).start();
new Thread(t1).start();

}

}
class MyThread1 implements Runnable{
private int ticket = 10;
@Override
//记得要资源公共,要在run方法之前加上synchronized关键字,要不然会出现抢资源的情况
public synchronized void run() {
for (int i = 0; i <10; i++) {
if (this.ticket>0) {
System.out.println("卖票:ticket"+this.ticket--);
}
}

}

}

输出:

A:0
B:0
A:1
B:1
B:2
A:2
B:3
A:3
A:4
B:4

Runnable:

实现方式:实现里面Runnable的run方法,用new Thread(Runnable target).start()方法来启动

(在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。此时观察Thread类,有一个构造方法:public Thread(Runnable targer)此构造方法接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现的多线程。)

public class Main {

public static void main(String[] args) {

//测试Runnable
MyThread1 t1 = new MyThread1();
new Thread(t1).start();//同一个t1,如果在Thread中就不行,会报错
new Thread(t1).start();
new Thread(t1).start();

}

}
class MyThread1 implements Runnable{
private int ticket = 10;
@Override
//记得要资源公共,要在run方法之前加上synchronized关键字,要不然会出现抢资源的情况
public synchronized void run() {
for (int i = 0; i <10; i++) {
if (this.ticket>0) {
System.out.println("卖票:ticket"+this.ticket--);
}
}

}

}

输出:

卖票:ticket10
卖票:ticket9
卖票:ticket8
卖票:ticket7
卖票:ticket6
卖票:ticket5
卖票:ticket4
卖票:ticket3
卖票:ticket2
卖票:ticket1

在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比继承Thread类有如下好处:

1.一个类只能继承一个父类,但是可以继承多个接口

2.实现Runnable,一个实例化对象可以创建多个线程,适合于资源的共享

原文地址:https://www.cnblogs.com/corolcorona/p/6672156.html