Thread

来源:互联网 发布:python编写exe程序 编辑:程序博客网 时间:2024/06/08 17:00

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
原创粉丝点击