volatile in thread

public class TestCalc {
      
        public static void main(String[] args)
        {
            class StoppableThread extends Thread
            {
                private volatile boolean stopped; // defaults to false
                @Override
                public void run()
                {
                while(!stopped)
                   System.out.println("running");
                }
                void stopThread()
                {
                    stopped = true;
                }
            }

                StoppableThread thd = new StoppableThread();
            thd.start();
            try
            {
                Thread.sleep(1000); // sleep for 1 second
            }
            catch (InterruptedException ie)
            {
            }
            thd.stopThread();
    }
}

 

posted on 2016-04-07 11:37  rojas  阅读(132)  评论(0编辑  收藏  举报