您的位置:首页 > 编程语言 > Java开发

Java基础 -- 线程

2006-11-09 13:29 337 查看
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){
}
}
}
};
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: