【发布时间】:2019-09-21 05:11:30
【问题描述】:
我正在尝试完成以下工作:
- 从用户那里获得两个输入(
length和amountOfCycles) - 创建一个包含
length线程数量的数组。每个都包含value范围内的整数[1, 100]。 - 循环
amountOfCycles + 1次数并在每次迭代时执行以下操作:- 打印数组的值。
- 根据其(循环)邻居更新数组中的每个值:
- 如果值小于两个邻居的值:将值增加 1
- 如果值大于两个邻居的值:将值减小 1
- 如果当前值小于或等于一个邻居,并且大于或等于另一个邻居:保持该值不变
根据它们的邻居更新这些值是多线程的原因。 请注意,这只是练习多线程的东西。通过简单地一起删除线程并创建数组的副本(which I already did),我可以轻松地完成上述操作。
到目前为止,这是我的代码:
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Main{
Cell[] cells;
CyclicBarrier barrier;
int length, amountOfCycles;
Main(){
Scanner stdin = new Scanner(System.in);
length = stdin.nextInt();
amountOfCycles = stdin.nextInt();
barrier = new CyclicBarrier(length);
cells = new Cell[length];
for(int i=0; i<length; i++)
cells[i] = new Cell(i);
}
public static void main(String[] args){
Main program = new Main();
program.start();
}
void start(){
for(int i=0; i<length; i++)
cells[i].run();
for(int cycle = amountOfCycles; cycle >= 0; cycle--)
System.out.println(Arrays.toString(cells));
}
class Cell implements Runnable{
int value,
index;
Cell(int i){
index = i;
value = (int)(Math.random() * 100) + 1; // Random integer within the range [1, 100]
}
@Override
public void run(){
try{
// Wait for the start of the cycle:
barrier.wait();
// Determine the increment for the value of this cell:
// Get the values of the neighbors:
int valueLeftNeighbor = cells[(length - index - 1) % length].value,
valueRightNeighbor = cells[(index + 1) % length].value,
// And create an increment-integer with default value 0:
increment = 0;
// If the current value is smaller than that of both neighbors:
if(value < valueLeftNeighbor && value < valueRightNeighbor){
// Increase the current value by 1
increment = 1;
}
// If the current value is larger than that of both neighbors:
if(value > valueLeftNeighbor && value > valueRightNeighbor){
// Decrease the current value by 1
increment = -1;
}
// If the current value is smaller than or equal to one neighbor,
// and larger than or equal to the other neighbor:
// Leave the value the same (so increment stays 0)
// Wait until every cell is done calculating its new value:
barrier.await();
// And then actually update the values of the cells
value += increment;
}catch(Exception ex){
System.err.println("Exception occurred! " + ex);
ex.printStackTrace();
}
}
@Override
public String toString(){
return Integer.toString(value);
}
}
}
基于this SO question and answer 和its accepted answer。
我上面的代码目前做了什么:
它使用随机值amountOfCycles + 1 次打印数组,但不会在周期之间更改任何值。这是由于我得到的IllegalMonitorStateExceptions。可能是因为我在某处需要synchronized(barrier){ ... },因为barrier 在Main 类中而不是Cell?但是,将其添加到 Cell 类的 run 方法会导致程序不再打印任何内容,也不会终止..
Here in my code above in an online compilers to see the current (incorrect) result.
我期望它做什么:
每次循环后修改数组中的值。
【问题讨论】:
标签: java multithreading async-await neighbours cyclicbarrier