I am trying to create a simple Java thread application, where one thread waits, and another 3 seconds After awake. However, I can not seem to work for it and I still do not know.
Expand the public class deadlock thread {Object lock = new object (); Public Static Zero Main (string [] algies) {// Vetra Thread Deadlock Hawker = New Deadlock () {@ Override Public Wired Run ({{System.out.println ("Better Start"); Synchronize (lock) {try {System.out.println ("Waiting to inform the battery ..."); Lock.wait (); System.out.println ("Pick!"); } Grip (Interrupted e) e.printStackTrace (); }}} // Run ()}; // Wakre Thread Deadlock waker = New Deadlock () {@ Override Public Wide Run ({{System.out.println ("Walker Start"); Synchronize (lock) {System.out.println ("Waker sleep for 3 seconds."); Try {Thread.sleep (3000); } Grip (Interrupted E) {} System.out.println ("Waker Notification ..."); Lock.notifyAll (); }} // Run}; Waiter.start (); Waker.start (); }
}
The output I get is:
Waiter started - Batler will wait to inform ... < Start Waker - Waker sleep for 3 seconds.
Waker notified ...
... and is going on forever. I expect the waiter thread to wake me up and to end the program.
Thank you
Your main problem is that 'lock' is a class instance property , So two deadlock instances do not share the same 'lock'. Therefore, there is no effect on the caller (at all) in the call to inform because it is waiting on a different object. The easiest solution is to make 'Lock' stable:
Fixed object lock = new object ();
... I also make it private and last for good measure.
The second issue is that by starting two threads together you do not really guarantee that the waiter will run first - I will add a short delay before starting waker.
No comments:
Post a Comment