多线程为什么不对??
下面是一个求素数的多线程事例,我写在一起为什么不对,我分开写就对了。为什么///
//fault,no output
public class TwoThread extends Thread
{
public TwoThread(String str)
{
super(str);
}
public static void prime(int a,int b)
{
int i,j,half,n;
for(i=a;i<b;i++)
{
n=i;
half=n/2;
for(j=2;j<=half;j++)
if(n%j==0)break;
if(j>half)System.out.print(i+" ");
}
}
public void run()
{
while(true)
{
try
{
if(Thread.currentThread().getName()=="thread1")
{
sleep(1000);
System.out.println(getName());
prime(1,1000);
}
else if(Thread.currentThread().getName()=="thread2")
{ sleep(1000);
System.out.println(getName());
prime(1000,2000);
}
System.out.println(getName());
}catch(InterruptedException e)
{}
}
}
public static void main(String[] args)
{
TwoThread thread1=new TwoThread("The First Thread");
TwoThread thread2=new TwoThread("The second Thread");
thread1.start();
thread2.start();
}
}
//分开写就对了
//FirstThread.java
class FirstThread extends Thread
{
public void run()
{
int i,j,half,n;
for(i=2;i<1000;i++)
{
n=i;
half=n/2;
for(j=2;j<=half;j++)
if(n%j==0)break;
if(j>half)System.out.print(i+" ");
}
}
}
//SecondThread .java
class SecondThread extends Thread
{
public void run()
{
int i,j,half,n;
for(i=1000;i<10000;i++)
{
n=i;
half=n/2;
for(j=2;j<=half;j++)
if(n%j==0)break;
if(j>half)System.out.print(i+" ");
}
}
}
public class TestThread
{
public static void main(String[] args)
{
FirstThread thread1=new FirstThread();
SecondThread thread2=new SecondThread();
thread1.start();
thread2.start();
}
}
还有关于输入输出的问题,输入输出流和要传输的数据到底是什么关系,把数据写入到输出流,控制台怎么显示数据的,也就是输出流和控制台的关系。