【发布时间】:2014-12-01 23:28:04
【问题描述】:
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
根据我的理解,当线程一启动时,它会在push 方法上获得一个锁。在push() 内,线程一会产生一段时间。但是当yield() 被调用时它会释放锁吗?现在当线程二启动时,线程二会在线程一完成执行之前获得锁吗?谁能解释一下线程一何时释放堆栈对象上的锁?
【问题讨论】:
标签: java multithreading thread-synchronization