Guest User

Untitled

a guest
Apr 25th, 2021
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. package me.nluk;
  2.  
  3. import java.util.List;
  4. import java.util.Scanner;
  5. import java.util.concurrent.Semaphore;
  6. import java.util.stream.Collectors;
  7. import java.util.stream.Stream;
  8.  
  9. public class Main {
  10.     public static void main(String[] args) throws InterruptedException{
  11.         Semaphore stdio = new Semaphore(1);
  12.         Semaphore inputReady = new Semaphore(2);
  13.         inputReady.drainPermits();
  14.         Input height = new Input("height", stdio, inputReady);
  15.         Input base = new Input("base", stdio, inputReady);
  16.         Output output = new Output(height, base, inputReady);
  17.  
  18.         List<Thread> threads = Stream.of(output, height, base).map(Thread::new).collect(Collectors.toList());
  19.         threads.forEach(Thread::start);
  20.         for(Thread t : threads){
  21.             t.join();
  22.         }
  23.     }
  24.  
  25.     public static class Output implements Runnable{
  26.         Semaphore outputSemaphore;
  27.         Input height, base;
  28.         Output(Input height, Input base, Semaphore outputSemaphore){
  29.             this.outputSemaphore = outputSemaphore;
  30.             this.height = height;
  31.             this.base = base;
  32.         }
  33.  
  34.         @Override
  35.         public void run() {
  36.             try {
  37.                 outputSemaphore.acquire(2);
  38.                 System.out.println("Result is "+(0.5 * height.input * base.input));
  39.             } catch (InterruptedException e) {
  40.                 e.printStackTrace();
  41.             }
  42.             finally {
  43.                 outputSemaphore.release(2);
  44.             }
  45.         }
  46.     }
  47.  
  48.     public static class Input implements Runnable{
  49.         Semaphore stdio, inputReady;
  50.         Long input;
  51.         String type;
  52.         Input(String type, Semaphore stdio, Semaphore inputReady){
  53.             this.type = type;
  54.             this.stdio = stdio;
  55.             this.inputReady = inputReady;
  56.         }
  57.         @Override
  58.         public void run() {
  59.             try {
  60.                 stdio.acquire();
  61.                 System.out.println("Enter "+type+" value: ");
  62.                 input = new Scanner(System.in).nextLong();
  63.             } catch (InterruptedException e) {
  64.                 e.printStackTrace();
  65.             }
  66.             finally {
  67.                 stdio.release();
  68.                 inputReady.release();
  69.             }
  70.         }
  71.     }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment