日期:2014-05-18  浏览次数:20718 次

线程关闭-变量赋值
我遇到一个蛮奇怪的问题,下面的程序竟然停不下来
大神们,我是哪个地方出问题了?求指导!


public class ServerTest {

    public static void main(String[] args) {
        Connector connector = new Connector();
        connector.run();
        connector.shutdown();
    }
    
    private static class Connector implements Runnable{

        private volatile boolean start = true;
        
        public void run() {
            while (start) {
                try {
                    Thread.sleep(100);
                    System.out.println("Respond to requests.");
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        public void shutdown () {
            this.start = false;
        }
    }
}
线程 Thread

------解决方案--------------------
一般Runnable都是放在一个Thread 里跑的
 Connector connector = new Connector();
Thread t = new Thread(connector);
t.start();
------解决方案--------------------
你这里
Connector connector = new Connector();
        connector.run();

不是线程,所以函数执行到 connector.run();一直在while循环里,下面一句话一直没有执行
connector.shutdown();

你的意思应该是启动线程。
 Connector connector = new Connector();
Thread t = new Thread(connector);
t.start();
 
------解决方案--------------------

     
&