Java基础 -- 线程

 

JAVA线程 基础一

 

PS:今天突然想看看关于线程的资料,就快速浏览了一下下面这本书,(高级话题没有看)

看了些基本概念,觉得书里小卡片形式的话写的非常不错,就摘录了一些(截图了)。

这本书很不错,又薄又容易懂(而且书中的例子非常有用)。推荐想看线程的朋友看看。

 

  Java基础 -- 线程_第1张图片

Java基础 -- 线程_第2张图片

Java基础 -- 线程_第3张图片

Java基础 -- 线程_第4张图片

PS:因为对上面一段话不是很理解,所以写了个小程序验证了一下。

/*

 *author: snail

 *date: 06-11-09

 */

public class IsThreadActive

{

 

       public static void main(String[] args)

       {

              OnlySleepThread t1 = new OnlySleepThread("sleepPig");

              OnlySleepThread t2 = new OnlySleepThread("sleepDog");

              printThreadsInfo("only main thread in current thread group.two SleepThread haven't slept yet");

              t1.start();

              t2.start();

              try{

                     Thread.sleep(3000);

                     }catch(InterruptedException e){

              }

              printThreadsInfo("two SleepThreads are sleeping now ,but they are alive!");

              try{

                     Thread.sleep(3000);

                     }catch(InterruptedException e){

              }

              printThreadsInfo("two SleepThreads are wakeup and finished!");

       }

 

       private static  void printThreadsInfo(String message){

              System.out.println("/n"+ message);

              Thread[] threads = new Thread[Thread.activeCount()];

              int count = Thread.enumerate(threads);

        for (int i=0; i<count; i++) {

            try {

                //threads[i].join();

                            System.out.println(threads[i]+"isAlive?"+threads[i].isAlive());

            }

            catch (Exception ex) { }

        }

       }

 

       private static class OnlySleepThread extends Thread

       {

              private boolean sleeping = true;

              public OnlySleepThread(String name){

                     super(name);

              }

 

              public void run(){

                     while(sleeping)

                     {

                            try{

                                   sleep(5000);

                                   sleeping = false;

                            }catch(InterruptedException e){

                            }

                     }

              }

       };

}

  Java基础 -- 线程_第5张图片

Java基础 -- 线程_第6张图片

Java基础 -- 线程_第7张图片

 

 

 

 

你可能感兴趣的:(java,thread,exception,Date,String,Class)