Kim Inopia
Kim Inopia

Reputation: 1

i'm creating a color game , how can i update the variable in run() method?

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
}

and this button starts/stops the random changes of the colour die but when i clicked the button the boolean starter becomes "false" but in the run() method it never changes

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");
                }
    }

Upvotes: 0

Views: 41

Answers (1)

David ten Hove
David ten Hove

Reputation: 2826

You are using 2 different threads to access the same local variable. In Java, each thread can cache the value of the variable for itsef. To prevent this, declare your variable as volatile:

volatile boolean starter = true;

See also http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

Upvotes: 2

Related Questions