/** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The thread * does not lose ownership of any monitors.
// 1、睡眠指定的毫秒数,且在这过程中不释放锁
* @param millis * the length of time to sleep in milliseconds * * @throws IllegalArgumentException * if the value of {@code millis} is negative
// 2、如果参数非法,报 IllegalArgumentException
* @throws InterruptedException * if any thread has interrupted the current thread. The * <i>interrupted status</i> of the current thread is * cleared when this exception is thrown.
* <p> Unless the current thread is interrupting itself, which is * always permitted, the {@link #checkAccess() checkAccess} method * of this thread is invoked, which may cause a {@link * SecurityException} to be thrown.
* <p> If this thread is blocked in an invocation of the {@link * Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link * Object#wait(long, int) wait(long, int)} methods of the {@link Object} * class, or of the {@link #join()}, {@link #join(long)}, {@link * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)}, * methods of this class, then its interrupt status will be cleared and it * will receive an {@link InterruptedException}. * * <p> If this thread is blocked in an I/O operation upon an {@link * java.nio.channels.InterruptibleChannel InterruptibleChannel} * then the channel will be closed, the thread's interrupt * status will be set, and the thread will receive a {@link * java.nio.channels.ClosedByInterruptException}. * * <p> If this thread is blocked in a {@link java.nio.channels.Selector} * then the thread's interrupt status will be set and it will return * immediately from the selection operation, possibly with a non-zero * value, just as if the selector's {@link * java.nio.channels.Selector#wakeup wakeup} method were invoked.
3、以上三种情况都不会发生时,才会把线程的中断状态改变
* <p> If none of the previous conditions hold then this thread's interrupt * status will be set. </p>
4、中断已经挂了的线程是无效的
* <p> Interrupting a thread that is not alive need not have any effect. * * @throws SecurityException * if the current thread cannot modify this thread * * @revised 6.0 * @spec JSR-51 */ publicvoidinterrupt(){ // 检查是否有权限 if (this != Thread.currentThread()) checkAccess();
synchronized (blockerLock) { // 判断是不是阻塞状态的线程调用,比如刚调用 sleep() Interruptible b = blocker; if (b != null) { interrupt0(); // Just to set the interrupt flag // 如果是,抛异常同时推出阻塞。将中断标志位改为 false b.interrupt(this); return; } } // 否则,顺利改变标志位 interrupt0(); }
/** * Tests whether the current thread has been interrupted. The * <i>interrupted status</i> 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). * * <p>A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return <code>true</code> if the current thread has been interrupted; * <code>false</code> otherwise. * @see #isInterrupted() * @revised 6.0 */ publicstaticbooleaninterrupted(){ return currentThread().isInterrupted(true); }
/** * Tests whether this thread has been interrupted. The <i>interrupted * status</i> of the thread is unaffected by this method. * * <p>A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return <code>true</code> if this thread has been interrupted; * <code>false</code> otherwise. * @see #interrupted() * @revised 6.0 */ publicbooleanisInterrupted(){ return isInterrupted(false); }
/** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */ privatenativebooleanisInterrupted(boolean ClearInterrupted);
看 Thread 的源码可以知道 yield () 为本地方法,也就是说 yield () 是由 C 或 C++ 实现的,源码如下:
/** * 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. * * <p> 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. * * <p> 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 the * {@link java.util.concurrent.locks} package. */ publicstaticnativevoidyield();
看代码注释知道:
当前线程调用 yield () 会让出 CPU 使用权,给别的线程执行,但是不确保真正让出。谁先抢到 CPU 谁执行。
当前线程调用 yield () 方法,会将状态从 RUNNABLE 转换为 WAITING。
比如:
publicstaticvoidmain(String[] args)throws InterruptedException { Runnable runnable = new Runnable() { @Override publicvoidrun(){ for (int i = 0; i < 10; i++) { System.out.println("线程:" + Thread.currentThread().getName() + " I:" + i); if (i == 5) { Thread.yield(); } } } }; Thread t1 = new Thread(runnable, "T1"); Thread t2 = new Thread(runnable, "T2"); t1.start(); t2.start(); }
执行这段代码会发现,每次的执行结果都不一样。那是因为 yield 方法非常不稳定。
8、join 方法
调用 join 方法,会等待该线程执行完毕后才执行别的线程。按照惯例,先来看看源码:
/** * Waits at most {@code millis} milliseconds for this thread to * die. A timeout of {@code 0} means to wait forever. * * <p> This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the * {@code this.notifyAll} method is invoked. It is recommended that * applications not use {@code wait}, {@code notify}, or * {@code notifyAll} on {@code Thread} instances. * * @param millis * the time to wait in milliseconds * * @throws IllegalArgumentException * if the value of {@code millis} is negative * * @throws InterruptedException * if any thread has interrupted the current thread. The * <i>interrupted status</i> of the current thread is * cleared when this exception is thrown. */ publicfinalsynchronizedvoidjoin(long millis)throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; // 超时时间不能小于 0 if (millis < 0) { thrownew IllegalArgumentException("timeout value is negative"); } // 等于 0 表示无限等待,直到线程执行完为之 if (millis == 0) { // 判断子线程 (其他线程) 为活跃线程,则一直等待 while (isAlive()) { wait(0); } } else { // 循环判断 while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。
Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。