求教,关于java中的线程同步问题。
在学习java时,看到线程的时候,书上说了一个关于线程同步的问题。可是我自己敲了一下运行了结果不一样。看了半天没看懂,特来求教。
程序代码:public interface StackInterface
{
public void push(int n);
public int[] pop();
}
public class SafeStack implements StackInterface
{
private int top = 0;
private int[] values = new int[10];
public void push(int n)
{
synchronized (this)
{
values[top] = n;
System.out.println("压入数字" + n + "步骤1完成");
top++;
System.out.println("压入数字完成");
}
}
public int[] pop()
{ synchronized (this)
{
System.out.print("弹出");
top--;
int[] test = {values[top], top };
return test;
}
}
}
public class PopThread implements Runnable
{
private StackInterface s;
public PopThread(StackInterface s)
{
this.s = s;
}
public void run()
{
System.out.print(s.pop()[1] + ":" +" "+ s.pop()[0]);
}
}
public class PushThread implements Runnable
{
private StackInterface s;
public PushThread(StackInterface s)
{
this.s = s;
}
public void run()
{
/*for(int i = 0; i < 10; i ++)
{
System.out.print(".");
}*/
int k = 15;
s.push(k);
}
}
public class TestSafeStack
{
public static void main(String[] args)
{
SafeStack a = new SafeStack();
a.push(3);
a.push(4);
PushThread r1 = new PushThread(a);
PopThread r2 = new PopThread(a);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}在class SafeStack 中已经用了synchronized修饰两个方法了。为什么还是会输出两个不同的结果?不是应该一个吗?
在class PushThread 中我加注释的部分,只是为了输出一列点而已。为什么会影响结果?
在结果中为什么有时候会显示两个“弹出”?









