010:“implements Runnable” vs. “extends Thread”?
Posted 氵冫丶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了010:“implements Runnable” vs. “extends Thread”?相关的知识,希望对你有一定的参考价值。
题目:“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的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。
以上是关于010:“implements Runnable” vs. “extends Thread”?的主要内容,如果未能解决你的问题,请参考以下文章
Java多线程extends Thread和implements Runnable