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里的,想请教各位这是为什么?