首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

控制线程打印有关问题

2012-03-13 
控制线程打印问题我有一个线程是打印1s,2s,3s,另外一个线程是监控输入(MultipleIO),如果输入-1就暂停所有

控制线程打印问题
我有一个线程是打印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();        }        }} 

热点排行