package Thread;
import java.util.LinkedList;
public class SynStack {
static LinkedList
Object lock = new Object ();
public synchronized void push (String x) {
synchronized (lock) {
System.out.println ("Add Object!");
list.addLast (x);
lock.notify ();
}
}
public synchronized String pop () throws Exception {
/ / changed synchronized (this) when , wait () method can release resources held ;
/ / Why is synchronized (list), synchronized (lock) would not be ?
synchronized (lock) {
if (list.size () <= 0) {
System.out.println ("No enough Objects!");
lock.wait ();
}
System.out.println ("Awaking!");
return list.removeLast ();
}
}
public static void main (String args []) {
final SynStack s = new SynStack ();
Thread thread = new Thread () {
public void run () {
s.push (new String ("First Thing!"));
}
};
Thread thread1 = new Thread () {
public void run () {
try {
System.out.println (s.pop ());
} catch (Exception e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}
}
};
thread1.start ();
try {
Thread.sleep (1000);
} catch (InterruptedException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}
thread.start ();
}
}
which SynStack class pop () and push methods are removed from the list or adding elements , the problem lies in the pop () method in the synchronized code block , in which the judge made a list of the size , if there is no element in list , then mobilize synchronized code block lock object wait () method ; Java multi-threading on wait () call with the following discussion : Perform the lock an object's wait () method , the thread releases the object lock into objects waiting pool. But I use SynStack the list or lock lock as an object will produce a deadlock , but will not use this .
baffled , we help solve what, appreciate it ! !
------ Solution ------------------------------------ --------
public synchronized void push (String x)
public synchronized String pop ()
in the definition of these two methods when it was declared as a synchronization method . Which is already locked up for this , followed by another on lock lock . May be the causes . Remove the synchronized method definition is try.
------ For reference only -------------------------------------- -
Thank you , remove the synchronized method can Oh

没有评论:
发表评论