频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

基于JDK5.0的一些Thread总结

来源: 作者: 出处:巧巧读书 2007-12-12 进入讨论组
下一页 1 2 3 

 在新的JDK5.0中,对thread做了一些改进,我通过阅读一些资料写下了下面的总结,请大家看看。

1.创建线程

 在java中实现多线程有两种方法,一个是直接继承Thread类,一个是实现Runnable接口,但是推荐的是第二种。因为在逻辑上应该要把一个线程要做的事情以及做这个事情的方法分开;对于Thread来讲,它只负责线程的操作,而具体要做的事情就应该放在Runnable中。但不管是那种方式,都要实现public void run()方法,但启动线程用start而不是run。

2.终止线程

 在1.0中,可以用stop方法来终止,但是现在这种方法已经被禁用了,改用interrupt方法。interrupt方法并不是强制终止线程,它只能设置线程的interrupted状态,而在线程中一般使用一下方式:

 while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}

 而被block的线程在被调用interrupt时会产生InterruptException,此时是否终止线程由本线程自己决定。程序的一般形式是:

 public void run()
{
try
{
. . .
while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
}
catch(InterruptedException e)
{
// thread was interrupted during sleep or wait
}
finally
{
cleanup, if required
}
// exiting the run method terminates the thread
}


 Thread.sleep方法也会产生InterruptedException,因此,如果每次在做完一些工作后调用了sleep方法,那么就不用检查isInterrupted,而是直接捕捉InterruptedException。

 在捕捉到InterruptedException时,如果没有其他的事情可做,最好做一下处理,不能用{}
1)

 void mySubTask()
{
. . .
try { sleep(delay); }
catch (InterruptedException e) { Thread().currentThread().interrupt(); }
. . .
}

或是
2)

 void mySubTask() throws InterruptedException
{
. . .
sleep(delay);
. . .
}

图 文 结 合:http://www.qqread.com/java/2007/06/f315566.html进入讨论组讨论。
下一页 1 2 3 
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章