Thread

1.  java.lang.Thread.yield() = sleep(0)

A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.

It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in thejava.util.concurrent.locks package.


当前线程并没有停止,只是由处理器重新调配,以防占用CPU过久。处理器此时可再次调用同一优先级的其他进程,亦可调用本线程。从调用的时刻起,所有的线程重新参与调配。

一般该方法用于调试或者测试,以助于重现竞争引起的bugs。


2.  sleep(long millis)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

当前线程在指定时间内不会运行,这段时间除该线程之外的线程参与调配,指定时间结束后,包括该线程之内的线程都参与调配。

但该方法并不释放对象锁,即对于Synchronized同步块,其他线程仍然不能访问共享数据,该方法需要捕捉异常。


3.java.lang.Thread.interrupted()

Tests whether the current thread has been interrupted. The interrupted status of the thread is cleared by this method. In other words, if this method were to be called twice in succession, the second call would return false (unless the current thread were interrupted again, after the first call had cleared its interrupted status and before the second call had examined it).

A thread interruption ignored because a thread was not alive at the time of the interrupt will be reflected by this method returning false.


4.wait

线程释放对象锁,synchronized块的共享数据可以被别的线程使用。

必须在synchronized函数或者synchronized block中调用,否则虽然编译能通过,但是会发生IllegalMonitorStateException异常。











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值