Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package me.nluk;
- import java.util.List;
- import java.util.Scanner;
- import java.util.concurrent.Semaphore;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- public class Main {
- public static void main(String[] args) throws InterruptedException{
- Semaphore stdio = new Semaphore(1);
- Semaphore inputReady = new Semaphore(2);
- inputReady.drainPermits();
- Input height = new Input("height", stdio, inputReady);
- Input base = new Input("base", stdio, inputReady);
- Output output = new Output(height, base, inputReady);
- List<Thread> threads = Stream.of(output, height, base).map(Thread::new).collect(Collectors.toList());
- threads.forEach(Thread::start);
- for(Thread t : threads){
- t.join();
- }
- }
- public static class Output implements Runnable{
- Semaphore outputSemaphore;
- Input height, base;
- Output(Input height, Input base, Semaphore outputSemaphore){
- this.outputSemaphore = outputSemaphore;
- this.height = height;
- this.base = base;
- }
- @Override
- public void run() {
- try {
- outputSemaphore.acquire(2);
- System.out.println("Result is "+(0.5 * height.input * base.input));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- finally {
- outputSemaphore.release(2);
- }
- }
- }
- public static class Input implements Runnable{
- Semaphore stdio, inputReady;
- Long input;
- String type;
- Input(String type, Semaphore stdio, Semaphore inputReady){
- this.type = type;
- this.stdio = stdio;
- this.inputReady = inputReady;
- }
- @Override
- public void run() {
- try {
- stdio.acquire();
- System.out.println("Enter "+type+" value: ");
- input = new Scanner(System.in).nextLong();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- finally {
- stdio.release();
- inputReady.release();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment