public class MyStack2 {
private int[] values = new int[10];
private int index = 0;
public synchronized void push(int x) {
if (index <= 9) {
values[index] = x;
Thread.yield();
index++;
}
}
public synchronized int pop() {
if (index > 0) {
index--;
return values[index];
} else {
return -1;
}
}
public synchronized String toString() {
String reply = "";
for (int i = 0; i < values.length; i++) {
reply += values[i] + " ";
}
return reply;
}
}
public class Pusher extends Thread {
private MyStack2 stack;
public Pusher(MyStack2 stack) {
this.stack = stack;
}
public void run() {
for (int i = 1; i <= 5; i++) {
stack.push(i);
}
}
}
public class Test {
public static void main(String args[]) {
MyStack2 stack = new MyStack2();
Pusher one = new Pusher(stack);
Pusher two = new Pusher(stack);
one.start();
two.start();
try {
one.join();
two.join();
} catch (InterruptedException e) {
}
System.out.println(stack.toString());
}
}
MyStack2
वर्ग के तरीकों के बाद से पर अवरोध खोल करता सिंक्रनाइज़ किए जाते हैं, मैं 1 2 3 4 5 1 2 3 4 5. के रूप में उत्पादन उम्मीद कर रहा था लेकिन उत्पादन होता है अनिश्चित। अक्सर यह देता है: 1 1 2 2 3 3 4 4 5 5थ्रेड synchronization- जब एक धागा एक वस्तु
मेरी समझ के अनुसार, जब धागा शुरू होता है तो यह push
विधि पर लॉक प्राप्त करता है। push()
के अंदर थ्रेड एक समय के लिए उपज। लेकिन क्या यह yield()
कहलाता है जब यह ताला जारी करता है? अब जब धागा दो शुरू हो गया है, तो क्या थ्रेड दो लॉक प्राप्त करेगा इससे पहले कि कोई निष्पादन पूरा करेगा? क्या कोई बता सकता है कि थ्रेड एक स्टैक ऑब्जेक्ट पर लॉक कब जारी करता है?
इस http://stackoverflow.com/questions/18635616/yield-inside-synchronized-block-lock-release-after-calling-yield – SimY4