我编写了一个程序,检查完成的9x9 Sudoku矩阵是否正确。我想创建线程来同时检查行,列和区域,以查看其中是否出现了数字1-9。我是使用Callable和lambda的新手。到目前为止,这是我的代码:
public class Sudoku {
public boolean testBoard(int[][] board) throws InterruptedException, ExecutionException {
List<Callable<Boolean>> tests = new ArrayList<>();
tests.add(() -> testCols(board));
tests.add(() -> testRegions(board));
tests.add(() -> testRows(board));
tests.add(() -> testSize(board));
/*Maybe store this threadPool in a field so you dont create it everytime*/
ExecutorService threadPool = Executors.newCachedThreadPool();
List<Future<Boolean>> results = threadPool.invokeAll(tests);
for (Future<Boolean> future : results) {
if (!Boolean.TRUE.equals(future.get())) {
return false;
}
}
return true;
}
// check that the board is 9 x 9
boolean testSize(int[][] board) {
if (board.length != 9) {
return false;
}
for (int i = 0; i < board.length; i++) {
if (board[i].length != 9) {
return false;
} else;
}
return true;
}
// check that the digits 1-9 each appear exactly once in the given array
boolean checkDigits(int[] array) {
if (array.length != 9) {
return false;
}
int[] counts = new int[10];
for (int i = 0; i
< array.length; i++) {
// invalid number
if (array[i] < 1 || array[i] > 9) {
return false;
}
// we have already seen this number
if (counts[array[i]] > 0) {
return false;
}
counts[array[i]]++;
}
return true;
}
// return true if all rows are correct
boolean testRows(int[][] board) {
for (int i = 0; i < board.length; i++) {
if (!checkDigits(board[i])) {
return false;
}
}
return true;
}
// return true if all columns are correct
boolean testCols(int[][] board) {
int[] tmp = new int[board.length];
for (int col = 0; col < board.length; col++) {
// fill a temp array with every element of the column
for (int row = 0; row < board.length; row++) {
tmp[row]
= board[row][col];
}
// check to make sure it has all the right digits
if (!checkDigits(tmp)) {
return false;
}
}
return true;
}
// return true if every region is correct
boolean testRegions(int[][] board) {
//loop through each region, passing the indices of the upper-left corner to the next method
//note that we increment row and column counters by 3 here
for (int row = 0; row < board.length; row += 3) {
for (int col = 0; col
< board.length; col += 3) {
if (!testRegion(board, row, col)) {
return false;
}
}
}
return true;
}
// test a specific region, given the upper left corner
boolean testRegion(int[][] board, int startRow, int startCol) {
int[] tmp = new int[board.length];
// fill a temporary array with every element of the region
int index = 0;
for (int row = startRow; row < startRow + 3; row++) {
for (int col = startCol; col < startCol + 3; col++) {
tmp[index]
= board[row][col];
index++;
}
}
// check if we have all of the right digits in the region
return checkDigits(tmp);
}
}
public class TestPuzzle {
public static void testpuzzle() throws FileNotFoundException, InterruptedException, ExecutionException{
Sudoku sudoku = new Sudoku();
String fileName = "SudokuRight.txt";//This is for the print statment
Scanner inputStream = null;
String[] line;
System.out.println("The file " + fileName + " contains the following sudoku puzzle:\n");
inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\NetBeansProjects\\Sudoku\\SudokuRight.txt"));
int[][] puzzle = new int[9][9];
int row = 0;
while (inputStream.hasNextLine()) {
line = inputStream.nextLine().split(",");
for (int i = 0; i < 9; i++) {
puzzle[row][i] = Integer.parseInt(line[i]);
}
row++;
}
for (int i = 0; i < 9; i++) {
System.out.println(Arrays.toString(puzzle[i]));
}
boolean result = sudoku.testBoard(puzzle);
System.out.println("Result: " + result);
if (result == true) {
System.out.println("This sudoku solution IS valid!");
} else if (result == false) {
System.out.println("This sudoku solution IS NOT valid!");
}
}
}
public class Main {
//This is the main method to check the validity of sudoku puzzles
public static void main(String[] args) throws FileNotFoundException, InterruptedException, ExecutionException {
TestPuzzle.testpuzzle();
}
}
有人试图教我有关使用callable和lambda的知识,但我仍然有些困惑。我的代码现在可以正确运行,但是在NetBeans中打印出结果之后,它会继续运行,直到我手动终止它为止。我不确定为什么吗?我以为我的代码中必须有这样一个语句块:
Callable<Boolean> callable = () -> Boolean.valueOf(testCols(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testRows(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testRegions(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testSize(board));
但是我不确定在哪里放置这些行?我不能将它们放在构造函数中,因为“ board”尚未初始化。我敢肯定这是一个简单的解决方法,因为我是新手,所以我只是停留在其中。有什么帮助吗?
最佳答案
根据我的评论,我认为您的问题是在将所有Callables添加到其中并调用它们之后,您尚未在执行程序服务上调用shutdown()
。我建议您这样做:
ExecutorService threadPool = Executors.newCachedThreadPool();
List<Future<Boolean>> results = threadPool.invokeAll(tests);
threadPool.shutdown(); // ******* add this! *********
一旦所有可调用对象完成其操作,这将有助于关闭threadPool。