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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© stormdzh 中级黑马   /  2013-9-11 10:16  /  1425 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

我写了两段小代码,代码虽小,但是觉得里面的问题很重要!所有,就附上代码来球解!
代码一:继承Thread
class TheredText
{
public static void main(String[] args)
{
  MyThread myThread=new MyThread();
  myThread.start();
}
}
class MyThread extends Thread
{
    MyThread(){};
int i=0;
boolean flag=true;
public void run()
{
   while(flag)
  {
       if(i<10000)
   {
     System.out.println("this is the input:" +i);
     i++;
      }
   else
    flag=false;
     }
}
}
----------------------------------------------------------------------
代码二:用Runnable接口
class RunnableTest1
{
public static void main(String[] args)
{
  new Thread(new TestRunnable()).start();
}
}
class TestRunnable implements Runnable
{
  public TestRunnable(){}
  int i=0;
  boolean flag=true;
  public void run()
{
      while(flag)
  {
       if(i<10000)
   {
     System.out.println("this is the input:" +i);
     i++;
      }
   else
    flag=false;
     }
    }
}
-------------------------------------------------------------------------------
两者的输出时一样的,同为:
this is the input:9701
this is the input:9702
this is the input:9703
this is the input:9704
this is the input:9705
this is the input:9706
this is the input:9707
this is the input:9708
this is the input:9709
this is the input:9710
this is the input:9711
this is the input:9712
this is the input:9713
this is the input:9714
this is the input:9715
this is the input:9716
this is the input:9717
this is the input:9718
this is the input:9719
this is the input:9720
this is the input:9721
this is the input:9722
this is the input:9723
this is the input:9724
this is the input:9725
首先解释一下,这个输出是没有问题的,它的输出时从1开始的,但是由于我用的是Editplus写的,运行的时候用的是window的控制台程序,又因为控制台的显示行数有限,所以就只显示所能容下的最后的那些部分,把循环条件控制到100就可以了,也可以让它打印了一部分就sleep一下,就可以看到一部分显示了,然后又被覆盖了。重点不是在这个问题,如题如下:
问题二:上面的两者那个更好?MyThread myThread=new MyThread();myThread.start();和new Thread(new TestRunnable()).start();都是启动线程,但是有什么区别?


评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 1

查看全部评分

5 个回复

倒序浏览
第一种实现方式是直接继承Thread类,所以可以直接调用Thread类的start()方法来开启线程,并调用run()方法来实现你自己所要执行的代码,而第二种方法是实现Runnable接口,与Thread类没有联系,所以要与new一个Thread来与Runnable相关联。在实现多线程代码时,建议使用第二种方式,因为可以实现多个线程使用同一个资源,比如买票系统。

评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 1

查看全部评分

回复 使用道具 举报 1 0
给你一个连接  太多了 没法贴过来 http://blog.csdn.net/benjaminzhang666/article/details/11110481
回复 使用道具 举报
这两种实现多线程的方式是有区别的:
首先在java中以面向对象的思想去理解就是继承只能是单继承而不能实现多继承;而实现接口还可以实现继承;这就是面向对象中的面向接口编程
的单一原则,从而更能提高程序的扩展性,同时也降低了程序中代码的耦合性,从而做到程序的高内聚低耦合;因此在开发是基本都会是用实现接口的方式来创建线程;

评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 1

查看全部评分

回复 使用道具 举报
1,实现Runnable接口的方式可以让run()所在的类提高扩展性,就是可以从其它类中继承一些有用的属性和方法,而继承Thread类的方式则不行,因为java是单继承,这应该是主要的一点

2,在使用上有时候会操作同一个数据,用Runnable接口方便操作

在开发中,一般用Runnable

评分

参与人数 1技术分 +1 收起 理由
EYE_SEE_YOU + 1

查看全部评分

回复 使用道具 举报
各位都是大神,受教了!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马