我目前正在使用简单的国际象棋AI(计算未来可能的回合,对其进行评分,选择最佳的回合,以及一些技巧,因此您不必计算每个回合)。该代码是用Java编写的,而我使用的是Netbeans。为了使计算更快,我使用了多线程。该代码大致如下所示:
现在我有一个奇怪的问题。该代码可以在我的PC上正常运行,但是当我在笔记本电脑上运行EXACT相同的代码时,在finish []数组的所有值都为true时,主要功能将无法继续工作。我已经对代码进行了一些更改,因此可以使用不同数量的线程进行尝试,但是结果始终相同。
我完全不知道这里发生了什么,如果你们中的任何人有任何答案和/或建议,我将不胜感激!
如果您需要更多信息,请询问,我将尽力而为。:)
(很抱歉可能会出现语法错误,英语不是我的母语,但我正在尽力而为。)
因此,我被要求显示我在程序中使用的一些代码:
(也许首先是警告,是的,我仍然是Java方面的Noob,这是我第一次使用线程,因此如果您看到我可能犯的严重错误,请不要感到震惊。xD)
主类看起来像这样:
public class Chess_ai_20 {
static boolean finished[] = new boolean[8];
Distributor[] Distributors = new Distributor[8];
...
public static void main(String[] args) {
boolean testing=false;
...
//some calculations and other stuff
...
Distributors[0] = new Distributor(...., "0"); //the String "0" will be the thread name.
Distributors[1] = new ...
...
Distributors[7] = new Distributor(...., "7");
for (int i = 0; i < 8; i++) {
Distributoren[i].start();
}
testing=false;
while(testing==false){
if(finished[0]==true && finished[1]==true && ... && finished[7]==true){
testing=true; //That's the point where I get stuck I suppose
}
}
System.out.println("I made it!");
}
public static void setFinished(int i) {
finished[i] = true;
System.out.println("finished [" + i + "] = " + finished[i]);
System.out.println(Arrays.toString(finished)); //To check how many values already are true
}
}
然后,我们当然得到了“分销商”类
public class Distributor extends Thread {
Thread t;
String threadname;
boolean running=false;
...
Distributor(......, String s) {
threadname=s;
...
...
}
@Override
public void start() {
running=true;
if (t == null) {
t = new Thread(this,threadname);
t.start();
}
}
@Override
public void run() {
if(running){
...
//Do the main calculations etc.
...
//All the Calculations habe been done at this point
Chess_ai_20.setFinished(Character.getNumericValue(threadname.charAt(0))); //Set the value of finished[] true in the main class
running=false;
}
}
}
正如其他人提到的那样,使用aFuture
会更简单易懂。以下是演示如何重写代码的代码段。查看实际使用的代码。
首先,编写一个Callable
以定义要执行的任务。
public class MyCallable implements Callable<Boolean> {
@Override
public Boolean call() {
// Do some job and return the result.
return Boolean.TRUE;
}
}
然后,您将此任务提交到Executor
。JDK中有很多执行程序。您想先阅读并发教程。
ExecutorService executor = Executors.newFixedThreadPool(Runtime
.getRuntime().availableProcessors());
List<Callable<Boolean>> callables = new ArrayList<>();
for (int counter = 0; counter < 8; counter++) {
callables.add(new MyCallable());
}
List<Future<Boolean>> futures = executor.invokeAll(callables);
for (Future<Boolean> future : futures) {
System.out.println(future.get()); // You'd want to store this into an array or wherever you see fit.
}
executor.shutdown();
请记住,执行者返回Callable
的期货与您提交(或添加)到的s的顺序相同Collection
(在本例中为ArrayList
)。因此,您不必担心返回索引,ID甚至是名称Thread
(如果已分配)的名称以映射相应的结果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句