如何在不暂停整个程序的情况下使方法暂停

如何在不暂停整个程序的情况下使方法暂停

本文介绍了如何在不暂停整个程序的情况下使方法暂停?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写一个程序,与玩家玩黑白棋/黑白棋.我写了一个方法来制作碎片翻转的简短动画-

So I'm writing a program that plays Reversi/Othello against a player. I wrote a method to make a short animation of the pieces flipping-

public void flip(int row, int col, Graphics window)
{
Color a;
if (pieces[row][col]==1)
    a = Color.black;
else
    a = Color.white;
for ( int size = 90; size>0; size-=2)
{
    try { Thread.sleep(11,1111); } catch (InterruptedException exc){}
    window.setColor(new Color( 0, 100, 0 ));
    window.fillRect(row*100+3, col*100+3, 94, 94);
    window.setColor(a);
    window.fillOval(row*100 + 5, col*100+5+(90-size)/2, 90, size);
}
if (a==Color.black)
    a=Color.white;
else
    a=Color.black;
for ( int size = 0; size<90; size+=2)
{
    try { Thread.sleep(11,1111); } catch (InterruptedException exc){}
    window.setColor(new Color( 0, 100, 0 ));
    window.fillRect(row*100+3, col*100+3, 94, 94);
    window.setColor(a);
    window.fillOval(row*100 + 5, col*100+5+(90-size)/2, 90, size);
}
}

它运行良好,看起来很棒,但问题是由于 thread.sleep 暂停了整个程序,它一次只能翻转一块.我可以做些什么来暂停该方法而不中断程序的其余部分?

It works well and looks great, but the problem is that since thread.sleep pauses the entire program, it can only flip one piece at a time. Is there something I can do to pause just that method without interrupting the rest of the program?

谢谢大家.新线程有效,但现在我遇到了不同的问题.翻转方法中的三个 setcolor 方法正在混淆.我认为这是因为有些线程将颜色设置为绿色,有些设置为黑色,有些设置为白色.我该如何解决这个问题?

Thanks everyone. The new thread worked, but now I have a different problem. The three setcolor methods in the flip method are getting mixed up. I think it's because some threads are setting the color to green, some to black and some to white. How do I fix this?

推荐答案

在这种情况下,您应该在单独的 Thread 中运行 flip.最简单的例子:

You should run flip in separate Thread in that case. The simplest example:

Thread t = new Thread(new Runnable() {
    public void run() {
        flip();
    }
});
t.start();

这篇关于如何在不暂停整个程序的情况下使方法暂停?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:56