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線程同步 - 什麼時候一個線程釋放物體
根據我的理解,當線程1開始時,它獲取push
方法的鎖。內線push()
線程一段時間產生。但是當調用yield()
時它釋放鎖嗎?現在當線程2啓動時,線程2完成執行之前線程2是否會獲得一個鎖?有人能解釋一下線程釋放堆棧對象上的鎖嗎?
看看這個http://stackoverflow.com/questions/18635616/yield-inside-synchronized-block-lock-release-after-calling-yield – SimY4 2014-10-07 13:57:45