我有一个学生正在为学校的期末项目开发西蒙游戏,我一整天都在尝试解决她的问题。 她正在尝试制作西蒙游戏。该程序随机选择一系列颜色,并通过将 4 个彩色按钮的颜色从常规颜色更改为白色几秒钟然后再返回来突出显示这些颜色。 编程不是一次突出显示一种颜色为白色,而是让所有颜色同时显示为白色。所以用户不知道顺序。
我一直在查找运行多个线程的问题,并尝试使用 .join() 函数。然而,当使用它时,没有颜色变白。
//突出显示当前数组中的颜色
public void play() {
//loop through the array and look at all the colours so far
for(int i=0; i<round;i++){
//red is the position in the array
if(colours[i]==1){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
//change the colour of the red button to white
redButton.setBackground(Color.WHITE);
redButton.setOpaque(true);
//wait
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
//change the colour back
redButton.setBackground(Color.RED);
redButton.setOpaque(false);
}
});
sleep.start();
}
//yellow
else if(colours[i]==2){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
yellowButton.setBackground(Color.WHITE);
yellowButton.setOpaque(true);
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
yellowButton.setBackground(Color.YELLOW);
yellowButton.setOpaque(false);
}
});
sleep.start();
}
//green
else if(colours[i]==3){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
greenButton.setBackground(Color.WHITE);
greenButton.setOpaque(true);
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
greenButton.setBackground(Color.GREEN);
greenButton.setOpaque(false);
}
});
sleep.start();
}
//blue
else if(colours[i]==4){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
blueButton.setBackground(Color.WHITE);
blueButton.setOpaque(true);
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
blueButton.setBackground(Color.CYAN);
blueButton.setOpaque(false);
}
});
sleep.start();
}
}
}
最佳答案
那里的代码基本上说明了这一点。
对于序列中的所有步骤,每个步骤启动一个线程。
然后每个线程(所有线程都很快启动,而不是在前一个线程完成之前启动。)将背景设置为白色 1 秒,然后返回。
通常您希望在后台更新 ui,以便可以继续交互,但在本例中您正在播放一个序列并且不需要任何输入。如果需要在后台更新,请将整个循环放入一个线程中,您将希望在该循环的迭代之间 hibernate 。否则只需在主线程中执行即可。一旦为用户播放完序列,它将把控制权传回事件循环以等待按下。
延迟也应该是 0.3s < t < .5s 1 秒太长了
关于java - 有没有一种快速方法可以在主代码继续之前关闭线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56401380/