Java Reference
In-Depth Information
7. values[index] = x;
8. Thread.yield();
9. index++;
10. }
11. }
12.
13. public int pop() {
14. if(index > 0) {
15. index--;
16. return values[index];
17. } else {
18. return -1;
19. }
20. }
21.
22. public String toString() {
23. String reply = “”;
24. for(int i = 0; i < values.length; i++) {
25. reply += values[i] + “ “;
26. }
27. return reply;
28. }
29. }
If two threads each push an int onto the stack at the same time, it is possible that data
in the stack will be corrupted, as demonstrated by the following Pusher class. The Pusher
class extends Thread and pushes fi ve int s onto an instance of MyStack in its run method:
public class Pusher extends Thread {
private MyStack stack;
public Pusher(MyStack stack) {
this.stack = stack;
}
public void run() {
for(int i = 1; i <= 5; i++) {
stack.push(i);
}
}
}
Search WWH ::




Custom Search