总结 :关于Thread类与Runnable接口的区别?(多线程两种实现方式的区别)
├ . Thread类是Runnalbe接口的子类 ;
├ . 如果要想实现多线程,那么必须要有线程主体类,主体类可以继承Thread类或实现Runnable接口,但是实现接口可以有效的避免单继承局限 ;
├ . 利用Runnable实现的多线程类,可以更加方便的表示出数据共享的概念 .
示例 : 通过实现Runnalbe接口来实现多线程
package example;
class MyThread implements Runnable{
private String title;
public MyThread (String title){
this.title = title;
}
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println("线程:" + this.title + " ,i = " + i);
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt1 = new MyThread("A");
MyThread mt2 = new MyThread("B");
MyThread mt3 = new MyThread("C");
Thread t1 = new Thread(mt1);
Thread t2 = new Thread(mt2);
Thread t3 = new Thread(mt3);
t1.start();
t2.start();
t3.start();
}
}
package example;
class MyThread extends Thread{
private String title;
public MyThread (String title){
this.title = title;
}
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println("线程:" + this.title + " ,i = " + i);
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt1 = new MyThread("A");
MyThread mt2 = new MyThread("B");
MyThread mt3 = new MyThread("C");
mt1.start();
mt2.start();
mt3.start();
}
}
示例 : 通过实现Runnable接口来实现数据共享
package example;
class MyThread implements Runnable{
private int ticket = 10;
@Override
public void run() {
for(int i=0;i<50;i++){
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "卖票:" + this.ticket --);
}
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
//三个线程,共享主体线程mt
Thread t1 = new Thread(mt,"A");
Thread t2 = new Thread(mt,"B");
Thread t3 = new Thread(mt,"C");
t1.start();
t2.start();
t3.start();
}
}
package example;
class MyThread extends Thread{
private int ticket = 10;
@Override
public void run() {
for(int i=0;i<50;i++){
if(ticket > 0){
System.out.println(Thread.currentThread().getName() + "卖票:" + this.ticket --);
}
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread(); //Thread类实现了Runnable接口
//三个线程,共享主体线程mt
Thread t1 = new Thread(mt,"A");
Thread t2 = new Thread(mt,"B");
Thread t3 = new Thread(mt,"C");
t1.start();
t2.start();
t3.start();
}
}