public class Msg {
public double i;
public double j;
public String orgStr = null;
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* A = B + C
* j = i + j
*/
public class Plus implements Runnable {
public static BlockingQueue<Msg> queue = new LinkedBlockingQueue<>();
@Override
public void run() {
while (true){
try {
Msg msg = queue.take();
msg.j=msg.i+msg.j;
Multiply.queue.add(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* D = A * B
* i = i * (i+j)
*/
public class Multiply implements Runnable{
public static BlockingQueue<Msg> queue = new LinkedBlockingQueue<>();
@Override
public void run() {
while (true){
try {
Msg msg = queue.take();
msg.i=msg.i*msg.j;
Div.queue.add(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* D = D / 2
* i = i * (i+j)/2
*/
public class Div implements Runnable {
public static BlockingQueue<Msg> queue = new LinkedBlockingQueue<>();
@Override
public void run() {
while (true){
try {
Msg msg = queue.take();
msg.i=msg.i/2;
System.out.println(msg.orgStr+"="+msg.i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 并行流水线
* 求 (B+C)*B/2
* Plus:A = B + C
* Multiply:D = A * B
* Div:D = D / 2
*
* i = i * (i+j)/2
*/
public class PStreamMain {
public static void main(String[] args){
new Thread(new Plus()).start();
new Thread(new Multiply()).start();
new Thread(new Div()).start();
for (int B = 1; B < 1000; B++) {
for (int C = 1; C < 1000; C++) {
Msg msg = new Msg();
msg.i = B;
msg.j = C;
msg.orgStr = "(("+B+"+"+C+")*"+B+")/2";
Plus.queue.add(msg);
}
}
}
//((1+1)*1)/2=1.0
//((1+2)*1)/2=1.5
//((1+3)*1)/2=2.0
//((1+4)*1)/2=2.5
//((1+5)*1)/2=3.0
//((1+6)*1)/2=3.5
//((1+7)*1)/2=4.0
//((1+8)*1)/2=4.5
//((1+9)*1)/2=5.0
//((1+10)*1)/2=5.5
//((1+11)*1)/2=6.0
//((1+12)*1)/2=6.5
//...
}