计算(B+C)*B/2。可以使用生产者消费者进行如下计算。
package od;
import java.util.concurrent.LinkedBlockingQueue;
public class TestTwoUtils {
public static void main(String[] args) {
//并行流水线
// 加法
final LinkedBlockingQueue<Msg> plusQ = new LinkedBlockingQueue<>();
final LinkedBlockingQueue<Msg> multiplyQ = new LinkedBlockingQueue<>();
final LinkedBlockingQueue<Msg> divQ = new LinkedBlockingQueue<>();
new Thread(() -> {
while (true) {
try {
Msg msg = plusQ.take();
msg.j = msg.i + msg.j;
multiplyQ.add(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
//乘法
new Thread(() -> {
while (true) {
try {
Msg msg = multiplyQ.take();
msg.i = msg.i * msg.j;
divQ.add(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
//除法
new Thread(() -> {
while (true) {
try {
Msg msg = divQ.take();
msg.i = msg.i / 2;
System.out.println(msg.orgStr + " = " + msg.i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
Msg msg = new Msg();
msg.i = i;
msg.j = j;
msg.orgStr = "((" + i + "+" + j + ")*" + i + ")/2";
plusQ.add(msg);
}
}
}
}
/**
* 定义一个在线程间携带结果进行信息交换的载体
*/
class Msg {
public double i;
public double j;
public String orgStr = null;
}
该博客演示了如何利用Java的并发工具类`LinkedBlockingQueue`实现生产者消费者模型,进行数学计算`(B+C)*B/2`。通过创建三个线程分别负责加法、乘法和除法操作,实现了并行计算的流水线处理。代码中定义了一个`Msg`类用于在不同线程间传递计算结果。
4747

被折叠的 条评论
为什么被折叠?



