aspose file tools*
The moose likes Threads and Synchronization and the fly likes Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread" Watch "Thread" New topic
Author

Thread

ricky gonzalez
Ranch Hand

Joined: Jun 30, 2000
Posts: 167
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

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
ricky gonzalez
Ranch Hand

Joined: Jun 30, 2000
Posts: 167
Hi, Jim, I thought everything was passed as reference. Or does that only work for parameteres?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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

Joined: Dec 14, 1998
Posts: 20582
    ∞

I'm moving this to the threads forum.


permaculture Wood Burning Stoves 2.0 - 4-DVD set
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread