知识大全 验证后台线程的java多线程技术

Posted

篇首语:博观而约取,厚积而薄发。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 验证后台线程的java多线程技术相关的知识,希望对你有一定的参考价值。

  这个程序验证了后台线程与用户线程的区别以及之间的关系 证明了只要所有的用户线程结束了 那么后台线程就将必须结束!

  import ncurrent TimeUnit;

  public class  Test 

  public  static void  main(String[] args)

  //将主线程的优先级设为最低 优先执行main线程创建的线程

  Thread currentThread() setPriority(Thread MIN_PRIORITY);

  Thread  myThread=new Thread(new Runnable()

  public void run()

  while(true)

  

  System out println( i will wait for you in shangling );

  try

  TimeUnit MILLISECONDS sleep( );

   catch (InterruptedException e)

  e printStackTrace();

  

  

  

  );

  myThread setDaemon(true); //设置后台线程一定要写在start()方法的前面 要不然是无效的

  myThread setPriority(Thread MAX_PRIORITY);

  myThread start();

  Thread userThread = new Thread(new Runnable()

  public void run()

  for(int i= ;i< ;i++)

  System out println( this is a user Thread );

  

  );

  userThread setPriority(Thread MAX_PRIORITY);

  userThread start();

  System out println( the main thread is end );

  

  

  在上面的程序中就能体会到 当用户线程都结束时 虽然后台线程(幽灵线程)是一个死循环 但是只要所有的用户线程都结束了 那么系统就会自动停止 要让后台线程执行得久一点 只有一个方法 那就是延长用户线程的运行时间 例如在main()方法中添加sleep()方法进行延时

cha138/Article/program/Java/gj/201311/27398

相关参考