读书人

为什么只有一个线程在运行,该如何处理

发布时间: 2012-01-03 22:16:06 作者: rapoo

为什么只有一个线程在运行
class MultiThread
{
public static void main(String[] args)
{
MyThread mt=new MyThread();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();

int index=0;
while(true)
{
if(index++==1000)
break;
System.out.println(Thread.currentThread().getName());
}
}
}

class MyThread implements Runnable
{
int index=0;
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+ ": "+index++);
}
}
}


运行时有四个线程在运行.当改成如下代码时,只有一个线程在运行.


class MultiThread


{
public static void main(String[] args)
{
MyThread mt=new MyThread();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
int index=0;
while(true)
{
if(index++==1000)
break;
System.out.println(Thread.currentThread().getName ());
}
}
}

class MyThread /*implements Runnable*/extends Thread
{
int index=0;
public void run()
{
while(true)
{
System.out.println(/*Thread.currentThread().*/getName()+ ": "+index++);
}
}
}


[解决办法]
继承的thread,那么要起多个线程必须有多个实例


[解决办法]
代码写错了哦
[解决办法]
以前老师好象讲过,implements runnable 与extends Thread 是不一样的

读书人网 >J2SE开发

热点推荐