我用java编写了一个小程序,用两个线程发送和接收一个数据文件。我希望这两个线程在同一个类中。一个线程发送该文件,另一个线程接收该文件。我已经为它写了代码,但是没有什么错误。你能帮我找出代码中的错误吗。我是一个学生和一个初学者在java,所以请原谅我,如果有任何愚蠢的错误。
import java.lang.Thread.*;
import java.io.*;
public class sendques implements Runnable
{
int i=0,c;
static Thread[] t= new Thread[2];
FileInputStream fis=new FileInputStream("ip.jpg");
FileOutputStream fos=new FileOutputStream("output.jpg");
sendques() {
for(i=0;i<2;i++){
t[i]=new Thread(this);
t[i].start();
System.out.println("Threads "+i);
}
}
void run() {
while(true) {
wait();
send();
}
}
void send() {
while((c=fis.read())!=-1) {
t[2].receive(c);
wait();
}
}
void receive(int d) {
while(c!=-1) {
fos.write(d);
t[1].notify();
}
}
public static void main(String arg[]) {
sendques sq=new sendques();
t[1].send();
System.out.println("Quiting..");
}
} 发布于 2012-07-02 23:24:32
不要使用notify,最好使用notifyAll,因为可能会发生活性故障,名为:错过信号。这将使您很难更正您的代码,下面是不同类的生产者/使用者实现的代码:
缓冲区类用于存储生产者和使用者之间共享的数据。他们有自己的类和一个在BoundedBuffer.java中可以找到的例子。它们不涉及繁重的计算任务,只是在两者之间传递消息。这是一个干净的实现,试着通过它。
https://stackoverflow.com/questions/10076697
复制相似问题