I started to learn about threads in Java , and I was trying to write a simple JFrame that would make use of them. I wanted to have two JLabel objects : one that would show the current time ( running in a separate thread ) , and another want that would be static ( and have the text “Time” ) . I also wanted to have two JButton objects that could pause/resume the “time thread” .
I had read about java’s wait,notify/notifyAll,and I wanted to use them,because the Thread methods stop/suspend/resume were marked as deprecated. Nothing to it, I thought . I was done with the code in about 10 minutes , and I wanted to test it . Surprisingly , after I paused the thread it wouldn’t resume when I pressed the button . After about an hour of debugging , I realized I wasn’t synchronising on the same object ( I had synchronize blocks in my code , and they were synchronizing on this , but this was not the same object throughout all the synchronized blocks ) . I don’t know why I had the idea that wait/notify/notifyAll would work regardless on what you synchronized on . You know the old saying , “2 hours of debugging can save 10 minutes of reading” . I’m not gonna post the code , it’s very ugly 🙂
Moral of the story : if you plan on writing multithreaded code , make sure you’re synchronizing on the right object .