当前位置: 代码迷 >> 综合 >> 010:“implements Runnable” vs. “extends Thread”?
  详细解决方案

010:“implements Runnable” vs. “extends Thread”?

热度:66   发布时间:2023-12-13 06:52:44.0

题目:“implements Runnable” vs. “extends Thread”?

具体实现方式如下程序

public class stackoverFlow {
      public static void main(String[] args) {new MyThread().start();new MyThread().start();new MyThread().start();System.out.println("#######################");MyRunnable myRunnable = new MyRunnable();new Thread(myRunnable).start();new Thread(myRunnable).start();new Thread(myRunnable).start();}} /*** 继承 Thread类实现多线程**/ class MyThread extends Thread {public MyThread() {super("MyThread");}public void run() {for(int i=0;i<10;i++){System.out.println("i = " + i +" MyThread "+Thread.currentThread().getName());}} }/*** 实现Runnable接口实现多线程**/ class MyRunnable implements Runnable{public void run() {for(int i=0;i<10;i++){System.out.println("i = " + i +" MyRunnable"+Thread.currentThread().getName());}} } 

测试输出

#######################
i = 0 MyThread MyThread
i = 0 MyThread MyThread
i = 1 MyThread MyThread
i = 2 MyThread MyThread
i = 3 MyThread MyThread
i = 4 MyThread MyThread
i = 5 MyThread MyThread
i = 6 MyThread MyThread
i = 7 MyThread MyThread
i = 8 MyThread MyThread
i = 9 MyThread MyThread
i = 0 MyThread MyThread
i = 1 MyThread MyThread
i = 2 MyThread MyThread
i = 3 MyThread MyThread
i = 4 MyThread MyThread
i = 5 MyThread MyThread
i = 6 MyThread MyThread
i = 7 MyThread MyThread
i = 8 MyThread MyThread
i = 9 MyThread MyThread
i = 1 MyThread MyThread
i = 2 MyThread MyThread
i = 3 MyThread MyThread
i = 4 MyThread MyThread
i = 5 MyThread MyThread
i = 6 MyThread MyThread
i = 7 MyThread MyThread
i = 8 MyThread MyThread
i = 9 MyThread MyThread
i = 0 MyRunnableThread-0
i = 0 MyRunnableThread-2
i = 1 MyRunnableThread-2
i = 2 MyRunnableThread-2
i = 3 MyRunnableThread-2
i = 4 MyRunnableThread-2
i = 5 MyRunnableThread-2
i = 6 MyRunnableThread-2
i = 7 MyRunnableThread-2
i = 8 MyRunnableThread-2
i = 0 MyRunnableThread-1
i = 1 MyRunnableThread-1
i = 2 MyRunnableThread-1
i = 3 MyRunnableThread-1
i = 4 MyRunnableThread-1
i = 5 MyRunnableThread-1
i = 6 MyRunnableThread-1
i = 7 MyRunnableThread-1
i = 8 MyRunnableThread-1
i = 9 MyRunnableThread-1
i = 1 MyRunnableThread-0
i = 9 MyRunnableThread-2
i = 2 MyRunnableThread-0
i = 3 MyRunnableThread-0
i = 4 MyRunnableThread-0
i = 5 MyRunnableThread-0
i = 6 MyRunnableThread-0
i = 7 MyRunnableThread-0
i = 8 MyRunnableThread-0
i = 9 MyRunnableThread-0

关系图
这里写图片描述

可以看出
Runnable可以避免由于java的单继承机制带来的局限。可以再继承其他类的同时,还能实现多线程的功能

本专题来源stackoverflow 标签是java的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。

  相关解决方案