【发布时间】:2014-09-26 14:53:07
【问题描述】:
我正在研究 Java 中的生产者-消费者问题,其中生产者在管道中写入斐波那契数,消费者通过管道阅读器使用它并检查它是否为素数。
问题在于下面给出的代码只生成了前 3 个斐波那契素数。
这有什么问题?
package fibonacciprime;
import java.io.*;
import java.lang.*;
public class FibonacciPrime extends Thread {
public static void main(String[] args) throws Exception {
//final PipedOutputStream pout=new PipedOutputStream();
//final PipedInputStream pin=new PipedInputStream();
final PipedWriter pwriter = new PipedWriter();
final PipedReader preader = new PipedReader(pwriter);
//pout.connect(pin);
Thread threadA=new Thread()
{
public void run()
{
for(int i=2;i<1000;i++)
{
synchronized(pwriter)
{
try
{
int temp=5*i*i-4;
int temp1=5*i*i+4;
int p=(int)Math.sqrt(temp1)*(int)Math.sqrt(temp1);
int q=(int)Math.sqrt(temp)*(int)Math.sqrt(temp);
if(p==temp1 || q==temp)
pwriter.write(i);
}catch(Exception e){e.printStackTrace();}
}
}
try {
pwriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread threadB = new Thread()
{
public void run()
{
int flag=0;
try
{
int temp;
while( ( temp = preader.read() ) != -1)
{
//int k=pin.read();
for(int i=2;i*i < temp;i++)
{
if(temp%i==0)
{
flag=1;
break;
}
}
Thread.sleep(100);
if(flag==0)
System.out.println(temp);
}
preader.close();
}catch(Exception e){e.printStackTrace();}
}
};
threadA.start();
threadB.start();
}
}
【问题讨论】:
-
@Satish Patel 您没有在 while 循环中重置
flag。一旦您在序列 (8) 中检测到非质数,您就可以将所有其他数字视为非质数。将声明int flag=0;移动到您的 while 循环中的第一行,您的程序就会运行。 -
@azurefrog 感谢您指出错误。
-
未来的提示:调试 println 语句是您的朋友。当您认为自己遇到了这样的通信问题时,请尝试在主要检查之前打印线路上的每个值。这会让你看到整个序列,这会让你注意到错误的实际位置。
标签: java multithreading fibonacci