一、Thread VS Runnable

  在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口;Thread类和Runnable接口都是在java.lang包中定义的。接下来本文给大家介绍下Java中Runnable和Thread的区别,当然啦,也算做是我整理的学习笔记吧,一起看看吧 

  • 实现Runnable接口方式可以避免继承Thread方式由于Java单继承特性带来的缺陷。具体什么缺陷呢?

  ①首先来从接口实现和类继承的区别来谈谈

  如果你想写一个类C,但这个类C已经继承了一个类A,此时,你又想让C实现多线程。用继承Thread类的方式不行了。(因为单继承的局限性),此时,只能用Runnable接口,Runnable接口就是为了解决这种情境出现的

  ②从Thread和Runnable的实现机制再来谈谈这个问题

  首先 ThreadRunnable 实际上是一种静态代理的实现方式。我们可以简单看一下源代码就了解了:

public interface Runnable {
    public abstract void run();
}

public class Thread implements Runnable {
    ...
    private Runnable target;
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
    public void run() {
        if (target != null) {
            target.run(); //代理的target的run方法
        }
    }
}

  另外一个我们知道线程启动是调用 thread.start() 方法,但是 start() 方法会调用 nativestart0()方法,继而由 JVM 来实现多线程的控制,因为需要系统调用来控制时间分片。

  现在我们可以深入理解一下两种线程实现方式的异同。

Class MyThread extends Thread(){
    public int count = 10;
    public synchronized void run(){
        while(count>0){
            count--;
        }
    } 
}

new Mythread().start(); //启动 n 个线程
new Mythread().start();

  这种实现方式实际上是重写了 run() 方法,由于线程的资源和 Thread 实例捆绑在一起,所以不同的线程的资源不会进行共享。

Class MyThread implements Runnable{
    public int count = 10;
    public synchronized void run(){
        while(count>0){
            count--;
        }
    } 
}
MyThread mt = new MyThread();
new Thread(mt).start();  //启动 n 个线程
new Thread(mt).start();

  这种实现方式就是静态代理的方式,线程资源与 Runable 实例捆绑在一起,Thread 只是作为一个代理类,所以资源可以进行共享。

  ③从 Java 语言设计者的角度来看

  Runnable 可以理解为 Task,对应的是具体的要运行的任务,而 Thread 对应某一个具体的线程运行的载体。综上,继承 Thread 来实现,可以说是不推荐的。

  实现Runnable的代码可以被多个线程(Thread实例)共享,适合于多个线程处理同一资源的情况。

  下面以典型的买票程序来说明这点(这里我为了让大家理解,没有用synchronized同步代码块,可能运行结果会不按正常出牌):

  ①通过继承Thread来实现

 1 package me.demo.thread;
 2 
 3 class MyThread extends Thread {
 4     private int ticketsCont = 5;// 一共有五张火车票
 5     private String name; // 窗口,也即是线程的名字
 6 
 7     public MyThread(String name) {
 8     this.name = name;
 9     }
10 
11     @Override
12     public void run() {
13     while (ticketsCont > 0) {
14         ticketsCont--; // 如果还有票就卖一张
15         System.out.println(name + "卖了一张票,剩余票数为:" + ticketsCont);
16     }
17     }
18 }
19 
20 public class TicketsThread {
21 
22     public static void main(String[] args) {
23     // 创建三个线程,模拟三个窗口卖票
24     MyThread mt1 = new MyThread("窗口1");
25     MyThread mt2 = new MyThread("窗口2");
26     MyThread mt3 = new MyThread("窗口3");
27 
28     // 启动这三个线程,也即是窗口,开始卖票
29     mt1.start();
30     mt2.start();
31     mt3.start();
32     }
33 }
View Code

相关文章:

  • 2021-06-26
  • 2022-12-23
  • 2021-12-10
  • 2022-01-15
  • 2021-06-11
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
猜你喜欢
  • 2021-10-25
  • 2021-08-11
  • 2021-12-03
  • 2021-12-01
  • 2021-06-30
  • 2022-12-23
  • 2021-06-30
相关资源
相似解决方案