Please xiaohaiz and predecessors in, a synchronization problem.

Category: Java SE
 
bjie560125
2013-08-20 05:17:15

Sponsored Links
import java.util. *;
class Producer implements Runnable {
private SyncStack theStack;
private int num;
private static int ; counter = 1;
public Producer (SyncStack s) {
theStack = s;
num = counter + +;
}
public void run () {
char c;
for (int i = 0; i <4; ; i + +) {
c = (char) (Math.random () * 26 + 'A');
theStack.push (c);
System.out.println ("Producer" + num + ":" + c);
try {
Thread. sleep ((int) (Math.random () * 300));
} catch (InterruptedException e) {}
}
}
}
class Consumer implements Runnable {
private SyncStack theStack;
private int num;
private static int counter = ; 1;
public Consumer (SyncStack s) {
theStack = s;
num = counter + +;
}
public void run () {
char c;
for (int i = 0; i <4; i + +) {
c = theStack.pop ();
System.out.println ("Consumer" + num + ":" + c);
try {
Thread.sleep ((int) (Math.random () * 300));
} catch (InterruptedException e) {}
}
}
}
class SyncStack {
private List buffer = new ArrayList (400);
public synchronized char pop () {
char c;
while (buffer.size () == 0) {
try {
this.wait ();
} catch (InterruptedException e) {}
}
c = ((Character) buffer.remove (buffer.size () -1)). charValue ();
return c;
}
public synchronized void push (char c) {
this.notify ();
Character charObj = new Character (c);
buffer.add (charObj);
}
}
public class SyncTest {
public static void main (String [] args) {
SyncStack stack = new SyncStack ();
Producer p1 = new Producer (stack);
Thread prodT1 = new Thread (p1);
prodT1.start ();
Producer p2 = new Producer (stack);
Thread prodT2 = new Thread (p2);
prodT2.start ();
Consumer c1 ; = new Consumer (stack);
Thread consT1 = new Thread (c1);
consT1.start ();
Consumer c2 = ; new Consumer (stack);
Thread consT2 = new Thread (c2);
consT2.start ();
}
}
This is directly from the SL-275 copy down, but I found that this program is actually running is wrong. Here is a run
results:
---------- java ----------
Producer1: B
Producer2: Y
Consumer1: Y
Consumer2: B
Consumer2: Q
Producer2: Q
Consumer1: J
Producer1: J
Consumer1: F
Producer1: F
Producer1: U
Consumer1: U
Producer2: X
Consumer2: X
Consumer2: B
Producer2: B
Normal Termination
Output completed (1 sec consumed).
please predecessors to see in the end is wrong there, thank you.

Sponsored Links

Domain and server ip had changed since 8/23/2013. Suspend the user registration and posts for program maintenance.