JAVA 多线程下进行压栈和弹栈,请问为什么弹栈POP方法没有效果?

public class MyStack {
    private int idx=0;
    private char[] data=new char[6];

    public int getIdx() {
        return idx;
    }
    public void push(char c){
        synchronized (this){
            data[idx]=c;
            idx++;
        }

    }
    public char pop(){
        synchronized (this){
            idx--;
            return data[idx];
        }

    }
}

public class A extends Thread{
    MyStack s;
    char c;
    public A(MyStack s){
        this.s=s;
    }
    public void run(){
        for(int i=0;i<100;i++){
            if(s.getIdx()<5){
                c=(char)(Math.random()*26+'A');
                s.push(c);
                System.out.println("A:push "+c);
            }
        }
    }
}

public class B extends Thread{
    MyStack s;
    char c;
    public B(MyStack s){
        this.s=s;
    }
    public void run(){
        for(int i=0;i<100;i++){
            if(s.getIdx()>0){
                c=s.pop();
                System.out.println("B:pop "+c);
            }
        }
    }
}

//Main方法路口
public class Main {
    public static void main(String[] args) {
        MyStack s = new MyStack();
        A a=new A(s);
        B b=new B(s);
        Thread t1=new Thread(a);
        Thread t2=new Thread(b);
        t1.start();
        t2.start();
    }
}

A:push B
A:push A
A:push L
A:push I
A:push T

结果项只有push里的,没有pop里的,想请教各位这是为什么?

你的 B 有输出。你用这个:

    public void run(){
        for(int i=0;i<100;i++){
            System.out.println("B #"+i+": index = "+s.getIdx());
            if(s.getIdx()>0){
                c=s.pop();
                System.out.println("B:pop "+c+" on index: "+s.getIdx());
            }
        }
    }

不常有,因为100个你限定了5个。20:1 机会。

B #0: index = 0
A:push K on index: 1
A:push Z on index: 1
A:push F on index: 2
A:push I on index: 3
A:push J on index: 4
A:push E on index: 5
B:pop K on index: 0
B #1: index = 5
B:pop E on index: 4
B #2: index = 4
B:pop J on index: 3
B #3: index = 3
B:pop I on index: 2
B #4: index = 2
B:pop F on index: 1
B #5: index = 1
B:pop Z on index: 0
B #6: index = 0

你瞧B出来了,它平时老是绕在 index 0.

再跑一次:

B #0: index = 0
A:push L on index: 1
A:push P on index: 1
A:push X on index: 2
A:push H on index: 3
A:push C on index: 4
A:push S on index: 5
B:pop L on index: 0
B #1: index = 5
B:pop S on index: 4
B #2: index = 4
B:pop C on index: 3
B #3: index = 3
B:pop H on index: 2
B #4: index = 2
B:pop X on index: 1
B #5: index = 1
B:pop P on index: 0

 

A: 我改了少许。

    public void run(){
        for(int i=0;i<100;i++){
            System.out.println("A #"+i+": index = "+s.getIdx());
            if(s.getIdx()<5){
                c=(char)(Math.random()*26+'A');
                s.push(c);
                System.out.println("A:push "+c+" on index: "+s.getIdx());
            }
        }
    }

这个A从来不放进 index 0 。