java TimeUnit synchronized demo

import java.util.concurrent.TimeUnit;
public class TestCalc
{
  private static boolean stopRequested=false;
  private static synchronized void requestStop()
  {
    stopRequested=true;
  }

  private static synchronized boolean stopRequested()
  {
    return stopRequested;
  }
  public static void main(String[] args)
    throws InterruptedException
   {
    Thread backgroundThread=new Thread
    (
      new Runnable(){
        public void run()
        {
          int i=0;
          while(!stopRequested()){
            i++;
            System.out.println("------------> "+ i );
          }
            
        }
      }
        
      );

    backgroundThread.start();

    //TimeUnit.SECONDS.sleep(1);  //建议用TimeUnit 
     backgroundThread.sleep(1000);
    
    requestStop();
  }
}

 

posted on 2016-04-04 10:44  rojas  阅读(166)  评论(0编辑  收藏  举报