你好!我有一点问题。我只学习多线程,但还不了解一切。
我有3个线程:1和2生成一个矩阵随机,并且在每一步之后它们通过管道矩阵元素发送类似参数。 3-d线程比较它们和写入结果,之后第1步和第2步进行下一步,它再次重复5次。
我的问题:我需要同步所有踏板才能正常工作。这个问题与生产者/消费者问题类似,但这里有2个生产者和1个消费者。
public class Producer1 extends Thread{
CyclicBarrier cbar;
public Producer1(CyclicBarrier c){
cbar=c;
new Thread(this).start();
}
private Random generator = new Random();
int []matrix1 = new int[1000];
private PipedWriter out = new PipedWriter();
public PipedWriter getPipedWriter() {
return out;
}
public void run() {
for(int i =0;i<5;i++){
matrix1[i]= generator.nextInt(10)+10;
System.out.println("matrix1["+i+"]= "+matrix1[i]);
try {
out.write(matrix1[i]);
cbar.await();
sleep(500);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
public class Producer2 extends Thread{
Random generator = new Random();
int []matrix2 = new int[1000];
CyclicBarrier cbar;
public Producer2(CyclicBarrier c){
cbar=c;
new Thread(this).start();
}
private PipedWriter out = new PipedWriter();
public PipedWriter getPipedWriter() {
return out;
}
public void run() {
for(int i =0;i<5;i++){
matrix2[i]= generator.nextInt(20)-10;
System.out.println("matrix2["+i+"]= "+matrix2[i]);
try {
out.write(matrix2[i]);
cbar.await();
sleep(500);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
Producer1 prod = new Producer1(new CyclicBarrier(2, new Consummer(prod,prod2)));
// here is a problem "prod2 cannot be resolved to a variable"
// How can i do it work??
Producer2 prod2 = new Producer2(new CyclicBarrier(2, new Consummer(prod,prod2)));
CyclicBarrier cb1 = new CyclicBarrier(2, new Consummer(prod,prod2));
prod.start();
prod2.start();
}
public class Consummer extends Thread{
private PipedReader el1;
private PipedReader el2;
public Consummer(Producer1 sender, Producer2 sender2) throws IOException {
el1 = new PipedReader(sender.getPipedWriter());
el2 = new PipedReader(sender2.getPipedWriter());
}
public void run() {
try {
while (true) {
System.out.println("Element1 : " + el1.read()+" Element2 : " + el2.read());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
for example :
i=0
1-> 10
2-> 5
3-> first is bigger =10
i++;
i=1;
1-> 3
2-> 5
3-> Second is bigger =5
i++;
i=2;
1-> 4
2-> 4
3-> both are equal = 4
i++;
.....
答案 0 :(得分:1)
可能还简化结构的一个选项是使用BlockingQueue
:
main
中,创建两个队列,每个队列传递给一个生产者,两个消费者
while (true) {
int[] matrix1 = queue1.remove();
int[] matrix2 = queue2.remove();
// process the two
}
答案 1 :(得分:0)
将barrier
传递给消费者并让它在打印之前等待:
while (true) {
barrier.wait();
System.out.println("Element1 : " + el1.read()+" Element2 : " + el2.read());
}