| Author |
On threads
|
Sid Robin
Ranch Hand
Joined: Nov 24, 2007
Posts: 53
|
|
public class Test { public static void main(String[] args) { final Foo f = new Foo(); Thread t = new Thread(new Runnable() { public void run() { f.doStuff(); } }, "Thread1"); Thread g = new Thread("Thread2") { public void run() { f.doStuff(); } }; t.start(); g.start(); } } class Foo { int x = 5; public void doStuff() { synchronized (this) { if (x < 10) { // nothing to do try { x += 5; System.out.println(Thread.currentThread().getName() + " is waiting."); this.wait(); System.out.println(Thread.currentThread().getName() + " is wait is over."); } catch (InterruptedException ex) { } } else { System.out.println("x is :" + x); if (x >= 10) { this.notify(); } } } } } how can g.start() access the synchronized and call notify() code when the lock of the object is possessed by wait() which was executed earlier ?
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
"Ripechancewoods" (previously "Siddalinga K M" and "siddu.sjce"), You've been warned twice before about your display name. If you check the JavaRanch Naming Policy, you will see that we need folks to use real (or at least real-looking) names, with a first and a last name. (Initials are fine for the first name, but not the last.)
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
Jan van Mansum
Ranch Hand
Joined: Oct 19, 2007
Posts: 74
|
|
The API makes for interesting reading :
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
(my emphasis) Hope this answers your question.
|
SCJP 1.4, SCWCD 1.4
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
"Siddu" - Please change your display name immediately to comply to the JavaRanch naming policy. Note that we take the naming policy seriously. If you do not change your name according to the policy, your account will be locked. You have been warned multiple times.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
 |
|
|
subject: On threads
|
|
|