日期:2014-05-20  浏览次数:20866 次

控制线程打印问题
我有一个线程是打印1s,2s,3s,另外一个线程是监控输入(MultipleIO),如果输入-1就暂停所有进程。我是使用了一个Boolean stop来控制线程的。可是为什么我输入-1后,打印线程里面的stop的值一直都没有变化呢?这样导致打印线程不停.难道两个线程里面的stop不指向同一个object吗?我该怎么样查看stop指向的object的地址呢
Java code
public class Core {
    public static void main(String[] args) throws Exception{
        Boolean stop = new Boolean(false);
        Thread display = new Thread(new Display(stop));
        Thread IO = new Thread(new MultipleIO(stop));
        display.start();
        IO.start();
    }
}


Java code
public class MultipleIO extends Thread{
    private Boolean stop;
    public MultipleIO(Boolean stop){
        this.stop =stop;
    }
    
    public void run(){
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        int i;
        while((i=scanner.nextInt())!=-1){
            System.out.println("not -1");
        }
        stop=true;
    }
}

Java code

public class Display extends Thread{
    private Boolean stop;
    
    public Display(Boolean stop){
        this.stop = stop;
    }
    
    public void run() {
        try {
            for(int i=1;i<Integer.MAX_VALUE&&stop==false;++i){
                Thread.sleep(1000);
                System.out.println(i+"s");
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


------解决方案--------------------
Java code

public class MultipleIO extends Thread{

    private Boolean stop;
    public MultipleIO(Boolean stop){
        this.stop =stop;
    }
    
    public void run(){
        Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        int i;
        while((i=scanner.nextInt())!=-1){
            System.out.println("not -1");
        }
        //stop=true;  
        setStop(true);
    }
    private void setStop(boolean stop){
        try{
            Field f = this.stop.getClass().getDeclaredField("value");
            f.setAccessible(true);
            f.set(this.stop, stop);
        }catch(Exception e){
            e.printStackTrace();
        }    
    }
}