Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- public class Third {
- static boolean end = false;
- static class Product {
- Character c;
- boolean isUsed() {return c == null;}
- boolean isReady() {return c != null;}
- }
- static class Consumer extends Thread {
- private final Product product;
- PrintWriter pw;
- public Consumer(Product product) {
- this.product = product;
- try {
- pw = new PrintWriter(new FileOutputStream(new File("output.txt")));
- } catch (FileNotFoundException e) {
- throw new IllegalStateException(e);
- }
- }
- @Override
- public void run() {
- while (!end) {
- synchronized (product) {
- while (!product.isReady()) {
- try {
- if(end) break;
- product.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- useProduct();
- product.notify();
- }
- }
- }
- void useProduct(){
- if(product.c == null) return;
- pw.print(product.c);
- product.c = null;
- pw.flush();
- }
- }
- static class Producer extends Thread {
- private final Product product;
- Reader r;
- public Producer(Product product) {
- this.product = product;
- try {
- r = new InputStreamReader(new FileInputStream(new File("input.txt")));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void run() {
- while (!end){
- synchronized (product){
- while (!product.isUsed()) {
- try {
- if(end) break;
- product.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- buildProduct();
- product.notify();
- }
- }
- }
- void buildProduct(){
- int in = 0;
- try {
- in = r.read();
- } catch (IOException e) {
- e.printStackTrace();
- }
- if(in == -1) {
- end = true;
- return;
- }
- product.c = (char) in;
- }
- }
- public static void main(String[] args) {
- Product p = new Product();
- Consumer c = new Consumer(p);
- Producer pr = new Producer(p);
- c.start();
- pr.start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement