Thread概念二

1,我们经常会说某些Class线程安全的,另外一些不是线程安全的。那么什么算是“线程安全”呢?
[quote]A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
[/quote]
要点:
1,一个Class在多个线程访问的时候,能够“行为正确”。
2,不论这些线程执行是scheduling或interleaving
3,并且在调用代码(calling code)上不需要额外的同步或其他的协调。

2,Thread机制
每个程序至少包含一个线程:run main方法的那个。其他的内部thread或者background thread也会在JVM初始化的时候开始。根据JVM的不同,这些thread数量不一。
Thread Construction
1)使用Runnable object来构造;Thread会在start的时候调用Runnable实现类的run()方法。
2)使用String来构造;这个String只是用来标识Thread,一般用于Debug,和Track,在实际的编程中贡献不大。
3)使用ThreadGroup来构造;
两种方式去用Thread:override Thread类,实现run方法;实现Runnable接口。 [url=http://g.oswego.edu/]Doug Lea[/url]推荐后者。理由是继承Thread有限制,而实现Runnable除了没有单继承的限制之外,还可以隔离代码。
Thread中的daemon作用不大。
在线程终止之后,再调用start会抛出异常InvalidThreadStateException。

调用Thread的join()方法让我迷惑了好长时间,惠普电话面试的时候就答错了,汗一把~~现在终于看到一个明确的答案。
其实非常简单。假设有个Thread t,caller来调用t.join()方法。这时候会把caller挂起,先执行线程t,等待t执行完(dead)之后,caller再继续执行。不过如果t.isActive()返回false的话,这个t.join()会直接返回。
t.join()还有一个带时间参数的overload方法。调用这个方法的话,会在这个时间段结束后返回,即使t还没有执行完。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值