This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread

 
ricky gonzalez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I saw this on Marcus's board and I find it interesting. Does anyone know why it doesn't work?
Hi, I have a GUI program that needs to be halted at times. So I have a inner class called Hold.
class Hold extends Thread{//1
Hold(){//2
System.out.println("in Hold...");
start();
}//*2
public void run(){//3
while(halt){//4
try{//5
System.out.println("in run...");
sleep(1000);
}//*5
catch(Exception error){//6
}//*6
}//4
}//3
}//*1
And I use it to halt like this:
Hold holdRightHere = new Hold();
Is that right? "halt" is a class boolean variable. Obviously not since it didn't work for me! But whats the problem?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you don't really show how halt is used outside this class or what exactly your program is doing, but I have a guess. Probably you need to declare halt as volatile, or control all access to halt using synchronized methods. Chances are your run() method is looking only at its own local copy of halt, which it copied from the class variable at the beginning of the method, and will copy back to the class varaible at the end of the method. Normally java assumes that no other threads will be mucking with your variables while a given method is using them, and this works OK. The volatile keyword is a way of telling the compiler that the variable value can change at any time, so it's necessary to look at the actual class variable (not a copy) each and every time it's mentioned in the code.
 
ricky gonzalez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Jim, I thought everything was passed as reference. Or does that only work for parameteres?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's only true for objects, not for primitive types: boolean, byte, short, char, int, long, float, double. Those are passed by value.
 
paul wheaton
Trailboss
Pie
Posts: 21598
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm moving this to the threads forum.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic