线程回顾 1

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);
   . . .
}

3.线程状态
New:当使用new创建一个线程时
Runnable: 调用start或是从blocked状态出来时
Blocked:sleep, block on input/output, try to acquire lock, suspend, wait.
Dead: 运行完成或有exception产生。

4.线程优先级
可以设置线程优先级,但是不能保证高优先级的线程就会被先运行

5.线程组
可以把多个线程加到一个线程组里面去,这样可以对这些线程进行一些统一的操作,例如
ThreadGroup g = new ThreadGroup(groupName)
...
g.interrupt(); // interrupt all threads in group g

6.为Uncaught Exceptions设置Handlers
在java 5.0中,可以为线程中产生的unchecked exception设置一个处理器,这个处理器必须实现UncaughtExceptionHandler接口。
可以调用线程实例的setUncaughtExceptionHandler方法为每个线程设置一个处理器,也可以调用Thread.setDefaultUncaughtExceptionHandler来为所有的线程设置一个默认的处理器。如果没有给每一个线程设置处理器,那线程会首先使用线程组的处理器,如果还没有再使用默认的处理器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值