PP-10-01-Rendezvous/Sum.java

58 lines
1.4 KiB
Java

/*-
package main
import "fmt"
func tasker (o, r chan int, d chan bool) {
o <- 1; o <- 2
fmt.Println (<-r); d <- true
}
func add (o, r chan int) {
r <- ((<-o) + (<-o))
}
func main () {
operand, result := make(chan int), make(chan int)
done:= make(chan bool)
go tasker (operand, result, done)
go add (operand, result)
<-done
}
*/
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Sum {
public static void main(String... args) throws InterruptedException {
var operand = new LinkedBlockingQueue<Integer>();
var result = new LinkedBlockingQueue<Integer>();
var done = new LinkedBlockingQueue<Boolean>();
(new Thread(() -> tasker(operand, result, done))).start();
(new Thread(() -> add(operand, result))).start();
done.take();
}
public static void tasker(BlockingQueue o, BlockingQueue r, BlockingQueue d) {
o.offer(3);
o.offer(2);
try {
System.out.println(r.take());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
d.offer(true);
}
public static void add(BlockingQueue<Integer> o, BlockingQueue<Integer> r) {
try {
r.offer(Integer.valueOf(o.take()) + Integer.valueOf(o.take()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}