My loop is not stopping when i set the number[0] = ten, the thread for the while loop can't see the number being changed when the jbutton is pressed, How do i fixed this? I believe the thread is being blocked.
public class A{
private int[] number = new number[1];
private number_game gui;
public A(){
}
public void thread_loop(){
gui = new number_game();
gui.the_game(number);
Thread nums = new Thread(){
public void run(){
while(number[0]!= 10){
if(number != 10)
System.out.println("wrong number")
}
};nums.start();
}
}
}
public class number_game extends Jframe{
......
public number_game(){}
/ creating gui
public void the_game(int [] guess){
.............
checkguess.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
guess[1] = 10;
dispose();
}
});
}
}
public class main{
public static void main(String[]args) {
A nums_play = new A();
nums_play.thread_loop();
}
}
I'm hoping that this is just some threading practice. To share values across threads you need to make sure that the access is synchronized properly, while there are a number of ways to do it, one of the simplest might be to use a
AtomicIntegerwhich takes care of all the multi-thread access functionality for you.I've also included a simple "lock" class which means that the
Threaddoesn't "free wheel" out of control and provides a means for the UI to alert the thread that a change has occurred, to which it can then process the value.All this is shared across the thread monitor and UI classes.
I strongly recommend having a look at the Concurrency Trail which covers this information in more detail
The example will increment the value (from
0) in steps of2, allow you to see the thread processing it until it reaches10If you wanted to, you could create a single class which emcampasses the
CommonLockandAtomicInteger, making the management slightly easier, but I'll leave that up to you