想验证一下多线程下数据共享出错的问题,在下面的程序中定义了一个简单的堆栈,并且两个线程向堆栈中压入数据和弹出数据。为了让它出错,在 MyStack 类中,当数据存入到数组之后,指针修改之前调用了 Thread.sleep 方法使之休眠。但后来将这一段代码加上同步锁之后,似乎没起到同步的作用啊代码如下:package nit.thread;class MyStack{
private int[] data = new int[10];
private int p = 0;
public void push(int value){
synchronized(this){
data[p] = value;
System.out.print("正在向位置 " + p + " 压入数据: " + value);
try{
Thread.sleep(100);
}catch(Exception ex){}
p++;
System.out.println(" 压入数据完成");
}
}
public int[] pop(){
p--;
return new int[]{data[p-1], p};
}
}class PushThread extends Thread{
private MyStack stack;
PushThread(MyStack stack){
this.stack = stack;
}
public void run(){
stack.push(100);
}
}class PopThread extends Thread{
private MyStack stack;
PopThread(MyStack stack){
this.stack = stack;
}
public void run(){
System.out.println(" 取出数据,top = " + stack.pop()[1] + " 完成");
}
}
public class TestStack {
public static void main(String[] args){
MyStack stack = new MyStack();
stack.push(10);
stack.push(20);

PushThread t1 = new PushThread(stack);
PopThread t2 = new PopThread(stack);
t1.start();
t2.start();
}
}