JAVA线程 基础一
PS:今天突然想看看关于线程的资料,就快速浏览了一下下面这本书,(高级话题没有看)
看了些基本概念,觉得书里小卡片形式的话写的非常不错,就摘录了一些(截图了)。
这本书很不错,又薄又容易懂(而且书中的例子非常有用)。推荐想看线程的朋友看看。






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程序演示了线程从启动到运行再到结束的不同状态,包括如何使用`isAlive()`方法判断线程是否处于活动状态。

被折叠的 条评论
为什么被折叠?



