我写了一个简单的程序,用来练习Java中的多线程。目标是测试数独解决方案是否有效:行、列或子网格中没有重复的数字。在这一点上,我并不关心条目必须是从1到9。当数独解决方案无效时,该程序运行良好。当数独解决方案有效时(在相同的输入上),程序只在某些时候工作。具体地说,"win“可能会打印,也可能不会打印。
我的程序通过创建RowThread、ColumnThread和GridThread来工作。它们中的每一个都分别检查解决方案是否具有有效的行、列和网格。当线程完成检查时,它调用SudokuTest中适当的setter方法,如果解决方案无效,该方法将调用Main中的end方法。如果线程未确定解决方案无效,则setter方法将记录行、列或网格已被检查,然后调用allChecked方法。allChecked检查是否检查了行、列和网格。如果是这样,那么解决方案是有效的,所以它调用Main.success(),它应该输出“win”。下面是我的主类:
public class Main{
public static void end(){//called by SudokuTest when the solution is invalid
System.out.println("fail");
System.exit(0);
}
public static void success() {//called by SudokuTest when the solution is valid
System.out.println("win");/*this line will not always print,
but it is reached in the debugger when I set a breakpoint.*/
System.exit(0);
}
public static void main(String[] args) {
int[][] sudokuSolution = new int[9][9];
int k = 0;
for (int i = 0; i < 9; i++) { //loop fills up a 2d array with the numbers 0-80, a valid solution
for (int j = 0; j < 9; j++) {
sudokuSolution[i][j] = k;
k++;
}
}
//sudokuSolution[1][1] = 0;//Testing an invalid solution
SudokuTest t = new SudokuTest();//
Runnable r = new RowThread(sudokuSolution, t);
Runnable c = new ColumnThread(sudokuSolution, t);
Runnable g = new GridThread(sudokuSolution, t);
new Thread(r).start();
new Thread(c).start();
new Thread(g).start();
}
}
我的RowThread类:
public class RowThread implements Runnable {
int[][] _sudoku;
SudokuTest _t;
public RowThread(int[][] sudoku, SudokuTest t) {
_sudoku = sudoku;
_t = t;
}
private void isFail() { //issue: how to get this info back to my Main function?
for(int i = 0; i < _sudoku.length; i++) {
for(int j = 0; j< _sudoku.length; j++) {
for (int k = j+1; k< _sudoku.length; k++) {
if (_sudoku[i][j] == _sudoku[i][k]) {
_t.setRow(true);
return;
}
}
}
}
_t.setRow(false);
}
@Override
public void run() {
isFail();
}
}
我的ColumnThread和GridThread类与RowThread相同,只是isFail()方法中的逻辑不同。我的SudokuTest类:
public class SudokuTest {
public boolean _rowBad;
public boolean _colBad;
public boolean _gridBad;
public boolean _rowChecked;
public boolean _colChecked;
public boolean _gridChecked;
public SudokuTest(){
}
public void setRow(boolean b) {
_rowBad = b;
_rowChecked = true;
if (b) {
Main.end();
}
}
public void setCol(boolean b) {
_colBad = b;
_colChecked = true;
if (b) {
Main.end();
}
}
public void setGrid(boolean b) {
_gridBad = b;
_gridChecked = true;
if (b) {
Main.end();
}
allChecked();
}
public void allChecked() {
if (_gridChecked && _colChecked && _rowChecked) {
Main.success();
}
}
}
发布于 2021-11-12 15:10:55
答:正如Maarten Bodewes指出的那样,我的错误是没有在setCol和setRow中调用allChecked。
https://stackoverflow.com/questions/69949844
复制相似问题