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