我正在创建一个彩色游戏,如何在run()方法中更新变量?

时间:2014-12-30 10:42:06

标签: java runnable actionevent

package myPackage;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;

public class Colorgame extends Applet implements Runnable , ActionListener{

boolean starter = true;

public void init(){
        this.setSize(800, 650);
        this.setLayout(null);
        this.setBackground(Color.pink);
        myFont = new Font("Times New Roman",Font.BOLD,20);
        new Thread(this).start();

        //button
        start = new Button("Start");
        start.setBounds(370, 610, 50, 30);
        start.addActionListener(this);

        add(start);
}


public void run(){
        while(starter){
        try{
            ranColor = rand.nextInt(6);
            switch (ranColor) {
            case 0:
                dieColor = Color.red;
                Thread.sleep(100);
                repaint();
                break;
            case 1:
                dieColor = Color.blue;
                Thread.sleep(100);
                repaint();
                break;
            case 2:
                dieColor = Color.green;
                Thread.sleep(100);
                repaint();
                break;
            case 3:
                dieColor = Color.yellow;
                Thread.sleep(100);
                repaint();
                break;
            case 4:
                dieColor = Color.orange;
                Thread.sleep(100);
                repaint();
                break;
            case 5:
                dieColor = Color.magenta;
                Thread.sleep(100);
                repaint();
                break;
            default:
                break;
            }
        }catch(Exception e){

        }
    }

}

public void paint(Graphics g){
    g.setColor(dieColor);
    g.fillRect(355, 90, 80, 80); //colour die
}

并且此按钮启动/停止颜色骰子的随机更改但是当我单击按钮时,布尔starter变为“false”但在run()方法中它永远不会改变

public void actionPerformed(ActionEvent e) { 
            if(e.getSource() == start){
                if(starter == true){
                    starter = false;
                    start.setLabel("Stop");
                }
                else if(starter == false){
                    starter = true;
                    start.setLabel("Start");
                }
    }

1 个答案:

答案 0 :(得分:2)

您正在使用2个不同的线程来访问同一个局部变量。在Java中,每个线程都可以为itsef缓存变量的值。要防止这种情况,请将变量声明为volatile:

volatile boolean starter = true;

另见http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html