我写了两段小代码,代码虽小,但是觉得里面的问题很重要!所有,就附上代码来球解!
代码一:继承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();都是启动线程,但是有什么区别?
|