A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 金兴 中级黑马   /  2012-4-9 13:28  /  2097 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class ThreadTest
{
        public static void main(String args[])
        {
                TestThread tt= new TestThread();
                Thread t= new Thread(tt);
                t.start();
                while(true)
                {
                        System.out.println("main thread is running");
                }
        }
}
class TestThread extends Thread //implements Runnable  //这里实现接口和继承的效果都是一样的, 这个怎么区分,什么时候用接口实现 ,什么时候用继承呢?
{
        public void run()
        {
                while(true)
                {
                        System.out.println(Thread.currentThread().getName() +
                        " is running");
                }
        }
}

2 个回复

倒序浏览
实现接口和继承都能实现多线程,但一般情况下建议使用实现接口,因为继承是有局限性的-----只能单继承,这样我们想用一个有着多级继承关系的类来实现多线程,就无法用继承Thread类来实现,因为它已经继承了其它的类,这时只能用实现接口,可见使用接口来实现多线程有着极大的灵活性,任意一个类不关它是否继承了除超类Object之外的其它类,都能通过实现Runnable接口来实现多线程。
回复 使用道具 举报
不错,支持下
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马