Witam, mam pewien kod (implementacja kolejki) - jeden wątek czyta po kolei znaki z pliku i dorzuca do kolejki, drugi z niej zdejmuje i zapisuje do drugiego pliku. Problem z tym, że konsument czyta mi tylko jeden znak i nie wiem dlaczego.
Może ktoś z Was mógłby zerknąć na kod i poratować?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package consumer;
import java.io.*;
import java.util.*;
import java.io.FileInputStream;
import java.util.Scanner;
/**
*
* @author Kamil
*/
class Queue{
int size;
char tab[];
int index = 0;
public Queue(int size){
this.size = size;
this.tab = new char[size];
}
synchronized void enqueue(char c){
if(this.isFull()){
try{
wait();
}catch(InterruptedException e){
System.out.print("Zlapano Interrupted");
}
}
this.tab[this.index] = c;
this.index++;
notify();
}
synchronized char dequeue(){
if(this.isEmpty()){
try{
wait();
}catch(InterruptedException e){
System.out.print("Zlapano Interrupted");
}
}
notify();
this.index--;
char r = this.tab[0];
for(int i = 1; i<this.size; i++){
this.tab[i-1] = this.tab[i];
}
return r;
}
public boolean isEmpty(){
if(this.index == 0){
return true;
} else {
return false;
}
}
public boolean isFull(){
if(this.tab.length == (this.index + 1)){
return true;
} else {
return false;
}
}
}
class Producer extends Thread {
Queue q;
String path;
Producer(Queue q){
this.q = q;
this.path = System.getProperty("user.dir")+"/src/consumer/file1.txt";
new Thread(this, "Producent").start();
}
public void run(){
try{
char c;
FileInputStream file = new FileInputStream(this.path);
while(file.available() > 0){
c = (char)file.read();
q.enqueue(c);
System.out.println("p: "+c);
}
} catch(FileNotFoundException e){
System.out.println("Plik nie istnieje");
} catch(IOException e){
System.out.println("Wyjatek IO");
}
// catch(InterruptedException e){
// System.out.println("Wyjatek Interrupted");
// }
}
}
public class Consumer extends Thread {
Queue q;
String path;
Consumer(Queue q){
this.q = q;
this.path = System.getProperty("user.dir")+"/src/consumer/file2.txt";
new Thread(this, "Konsument").start();
}
public void run(){
try{
char c;
FileOutputStream file = new FileOutputStream(this.path);
c = q.dequeue();
file.write(c);
System.out.println("c: "+c);
} catch(FileNotFoundException e){
System.out.println("Plik nie istnieje");
} catch(IOException e){
System.out.println("Wyjatek IO");
}
}
public static void main(String[] args) {
Queue queue = new Queue(5);
Producer p = new Producer(queue);
Consumer c = new Consumer(queue);
}
}