This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Well this is the third time I ask this question, this time I try give you enough information and I have also read from the beginning of the java tutorial on sun's website to the lesson about threads. In my last post you said i should read about event listeners but i don't believe the problem is in there.
I want an Integer to rise by 1 every second while I have left arrow button pressed and then stop rising when I relase it. I tried somehow make an inner class which would be the tread which starts and stops when I press and relase the left arrow button.
But when I run the program (I have a println method which shows the value of heading360) it first prints out 2's, then when I press left arrow it prints 0's for like 1 sec and then prints 1's till I end the program. I believe the problem is that I don't really undertand how threads work. I read from the tutorial but I couldn't use the examples for this.
Below is the code I'm using. I have removed parts of the code. I'll post more if I have forgot to write a part you need to see.
I see three problems with your code, on first sight:
- Thread.sleep gets the time in ms - 100ms is 0.1s, not 1s
- you don't print the value of the heading variable that gets changed in your thread, but the value that you copied in the keyDown method
- you are accessing the heading field from two different threads - the one that changes it, and the one that reads it to print it. You need to synchronize that access to work reliably. With other words, as written the access to heading is not threadsave.
Hope this helps.
Moving this to Threads and Synchronization, where there are more experts able to help you...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Mar 04, 2005
YAY!! IT WORKED
The problem was here:
I changed it to if (allDone == true) then the thread worked but i could only run it once. Then made Thread = null and it worked
Here is the code i use now. Could someone check it if I could do something better. Especially the synchronized methods because I have no idea if i put them to the right places.