在Java语言中,从JDK1.0开始就有多线程,在多线程的实现上面有多种形式,那么继承Thread类和实现Runnable接口两种实现方式的有哪些区别?

区别:
1.Thread 类是实现了Runnable,使用Runnable接口比继承Thread类相比,更好的解决单继承问题。
2.Runnable接口实现的多线程比Thread类实现的多线程更加清楚的描述数据共享的概念。

简单实例演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.devnp;

/**
* Created by duliu on 26/8/2017.
*/

class Thread1 implements Runnable{

private int ticket = 10 ;

public void run() {
for (int i = 0; i < 10 &amp;&amp; ticket >0; i++) {
System.out.println("Ticket1 count : " + ticket--);
}

}
}

class Thread2 extends Thread{
private int ticket = 10 ;

@Override
public void run() {
for (int i = 0; i < 10 &amp;&amp; ticket >0; i++) {
System.out.println("Ticket2 count : " + ticket--);
}
}
}

public class ShareDataDemo {
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
new Thread(thread1).start();
new Thread(thread1).start();
new Thread(thread1).start();

new Thread2().start();
new Thread2().start();
new Thread2().start();

}
}

通过运行结果可以发现,在实现Runnable接口上面,在共享的数据上面更加清楚。