public class Test_Thread{
public static void main(String[] args)throws Exception{
StackSort sign=new StackSort();
OneThread one=new OneThread(sign);
TwoThread two=new TwoThread(sign);
one.start();
two.start();
}
}
class StackSort{
private int index=0;
private char[] data=new char[20];
void push(char c){
data[index]=c;
index++;
}
char pop(){
char c=data[index];
index--;
return c;
}
int getIndex(){
return this.index;
}
char[] getData(){
return this.data;
}
}
class OneThread extends Thread {
StackSort sign;
OneThread (StackSort sign){
this.sign=sign;
}
public void run(){
sign.push('a');
sign.push('b');
sign.push('c');
sign.push('d');
sign.push('e');
System.out.print("OneThread:");
for(int i=0;i<sign.getIndex();i++){
System.out.print(sign.getData()[i]+" ");
}
System.out.println("index:"+sign.getIndex());
}
}
class TwoThread extends Thread{
StackSort sign;
TwoThread (StackSort sign){
this.sign=sign;
}
public void run(){
System.out.print("pop:");
sign.push('f');
sign.push('g');
System.out.print(sign.pop()+" ");
sign.push('h');
sign.push('i');
System.out.println(sign.pop());
sign.push('j');
if(sign.pop()=='j')System.out.println("true");
System.out.print("TwoThread:");
for(int i=0;i<=sign.getIndex();i++){
System.out.print(sign.getData()[i]+" ");
}
}
}
运行结果为:
OneThread:a b c d e index:5
pop:
TwoThread:a b c d e f h j 问题:
为何pop:后面没有打印出pop()方法返回的值?
在if(sign.pop()=='j')System.out.println("true");后为什么j还能在下面的循环打印出来?

解决方案 »

  1.   

    为什么总是先执行System.out.print
    然后才sign.push('');
      

  2.   

    index 的问题。pop出来的是char型的默认值。
      

  3.   

    粗看了一下,楼主这是两个线程,两个线程随机的交替执行。
    打印pop:后,又转到了TwoThread那个线程去了。
    第二问题也是类似的,执行完if(sign.pop()=='j')后,转去执行了OneThread 线程,使index又加1了。楼主如果明白两个线程不是顺序执行,而是由cpu随机切换执行,就理解输出了。cup可能执行了一个线程一半,而又切到另一个线程去执行。同一个程序,执行多次,可能结果是不一样的。
      

  4.   

    你搞错了System.out.print();是先执行方法的执行参数是我一时疏忽了index是指向后一个值导致的
      

  5.   

    你想太复杂了吧你说的是有可能出现。但出现的次数很少。在单核的xp系统我执行了很多次都不会出现你说的。。主要问题是index的值问题
      

  6.   

    首先,你这个程序整个就没有synchronized,很容易运行出问题来。其次,你的pop是个Bug程序,应该是 --index,然后才输出。因为你push的时候是设置后才++。修改:
    char pop(){
      if (index > 0) return data[--index];
      throw new RuntimeException("EMPTY!");
    }
    改正后的结果是(OneThread和TwoThread串行执行的话):
    OneThread:a b c d e index:5
    pop:g i
    true
    TwoThread:a b c d e f h j 是否如你所愿?