在Java中后台运行的线程

问题描述:

我写在Java中的国际象棋程序。到目前为止,事情正在沿着罚款来,但我确实有更新我的UI的一个问题。

I'm writing a chess program in java. So far things are coming along fine but I do have a problem with updating my UI.

下面是code从它扩展JPanel类器ChessBoard片段。这是当用户试图使一招叫:

Here's a snippet of code from class ChessBoard which extends JPanel. This is called when a user tries to make a move:

if ( isLegalMove( aMove ) ) { // If the move's legal
    makeMove( aMove ); // Make that move
    select = null; // Reset some info
    drag = null;
    toggleTurn(); // Change turns
    generateMoves( 0 ); // Get legal moves for CPU
    repaint(); // Redraw board
    thread.run(); // Run chess algorithm
}

线程呼吁我的棋盘例如运行。该发现此举可能需要几秒钟就转会决定的算法。

The thread is calling "run" on my instance of ChessBoard. The algorithm that finds the move can take several seconds to decide on a move.

我想为我的UI更新以反映用户的举动,然后运行该算法。这就是为什么我运行一个单独的线程的算法。但我的UI不会被更新,直到计算机也使一招。

I would like for my UI to update to reflect the user's move and then run the algorithm. That's why I run the algorithm on a separate thread. But my UI is not being updated until the computer also makes a move.

因此​​,如果用户点击一个空间,送了一块在那里,屏幕冻结,然后一下子把一块已经转移,但计算机移动也并再次将是玩家的回合。

So if the user clicks a space to send a piece there, the screen freezes and then all of a sudden the piece has moved but the computer has moved also and it is again the player's turn.

任何帮助将大大AP preciated。

Any help will be greatly appreciated.

thread.run()是要在线程的run方法执行code上当前线程。你想 thread.start()

thread.run() is going to execute the code in the thread's run method on the current thread. You want thread.start().

相关的JavaDoc

重绘方法实际上并不立即重新绘制。它基本上告诉JPanel的,它应该很快重绘自己。然后你继续在同一线程上并计算AI的举动,这将冻结窗口,因为Swing是不是多线程的。

The repaint method doesn't actually repaint immediately. It basically tells the JPanel that it ought to repaint itself soon. Then you go ahead on the same thread and calculate the AI's move, which will freeze the window because Swing isn't multi-threaded.