黑马程序员技术交流社区

标题: 判断线程是否启动,求出14,16,21行中isAlive()的值? [打印本页]

作者: lovecx24    时间: 2013-12-5 13:26
标题: 判断线程是否启动,求出14,16,21行中isAlive()的值?
  1. public class StartThreadDemo extends Thread{
  2.   public void run(){
  3.     for(int i=0;i<2;i++){
  4.          printTName();
  5.       }
  6. }
  7. public void printTNmae(){
  8.     String name=Thread.currentThread().getName();
  9. System.out.println("当前线程的名字 " + name);
  10. }
  11. public static void main(String[] args){
  12. StarttHREADdEMO T = NEW StartThreadDemo();
  13. t.setName("test thread");
  14. System.out.println("调用start()方法之前,t.isAlive() = " + t.isAlive());
  15. t.start();
  16. System.out.println("调用start()方法之后,t.isAlive() = " + t.isAlive());
  17. for(int i=0;i<2;i++){
  18. t.printTName();
  19. try{
  20.     Thread.sleep(200);
  21. System.out.println("线程休眠时, t.isAlive() = " + t.isAlive());
  22. }catch(InterruptedException e){
  23.   e.printStackTrace();
  24. }
  25. }
  26. }
复制代码

判断线程是否启动,求出14,16,21行中isAlive()的值?


作者: lichao    时间: 2013-12-6 21:16
这时对你程序的修改
  1. public class StartThreadDemo extends Thread{
  2.           public void run(){
  3.                 for(int i=0;i<2;i++){
  4.                          printTName();
  5.                   }
  6.         }
  7.         public void printTName(){
  8.                 String name=Thread.currentThread().getName();
  9.         System.out.println("当前线程的名字 " + name);
  10.         }
  11.         public static void main(String[] args){
  12.                 StartThreadDemo t = new StartThreadDemo();
  13.                 t.setName("test thread");
  14.                 System.out.println("调用start()方法之前,t.isAlive() = " + t.isAlive());
  15.                 System.out.println("........................");
  16.                 t.start();
  17.                 System.out.println("调用start()方法之后,t.isAlive() = " + t.isAlive());
  18.                 System.out.println("........................");
  19.                 for(int i=0;i<2;i++){
  20.                 t.printTName();
  21.                         try{
  22.                                 Thread.sleep(200);
  23.                         System.out.println("线程休眠时, t.isAlive() = " + t.isAlive());
  24.                         System.out.println("........................");
  25.                         }catch(InterruptedException e){
  26.                           e.printStackTrace();
  27.                         }
  28.                 }
  29.         }
  30. }
复制代码

这时运行结果:

调用start()方法之前,t.isAlive() = false
........................
调用start()方法之后,t.isAlive() = true
........................
当前线程的名字 main
当前线程的名字 test thread
当前线程的名字 test thread
线程休眠时, t.isAlive() = false
........................
当前线程的名字 main
线程休眠时, t.isAlive() = false
........................




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2