Java多线程与并发-8.8 yield函数和interrupt函数

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/tanwenfang/article/details/92404061

1,yield函数
当调用Thread.yield函数时,会给线程调度器一个当前线程愿意让出CPU使用的暗示,但是线程调度器可能会忽略这个暗示。

yield()不会对当前线程的锁造成影响。

2,interrupt函数
如何中断线程?
1,已经被抛弃的方法:stop(),suspend(),resume();
2,目前使用的方法:
(1)调用interrupt(),通知线程应该中断了
<1>如果线程处于被阻塞状态,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常。
<2>如果线程处于正常活动状态,那么会将该线程的中断标志设置为true。被设置中断标志的线程将继续正常运行,不受影响。
(2)需要被调用的线程配合中断
<1>在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程。
下面看一个例子,看程序是如何停止线程的:

package thread;
public class InterruptDemo {
	public static void main(String[] args) throws InterruptedException {
		Runnable interuptTask = new Runnable() {
			@Override
			public void run() {
				int i = 0;
				try {
					// 在运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程
					while (!Thread.currentThread().isInterrupted()) {
						Thread.sleep(100);
						i++;
						System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") loop " + i);
					}
				} catch (InterruptedException e) {
					System.out.println(Thread.currentThread().getName() + " (" + Thread.currentThread().getState() + ") catch InterruptedException");
				}
			}
		};
		Thread t1 = new Thread(interuptTask,"t1");
		System.out.println(t1.getName() + " (" + t1.getState() + ") is new.");
		
		t1.start();
		System.out.println(t1.getName() + " (" + t1.getState() + ") is started.");
		
		Thread.sleep(300);
		t1.interrupt();
		System.out.println(t1.getName() + " (" + t1.getState() + ") is interrupted");
		
		Thread.sleep(300);
		System.out.println(t1.getName() + " (" + t1.getState() + ") is interrupted now");
	}
}

输出:

t1 (NEW) is new.
t1 (RUNNABLE) is started.
t1 (RUNNABLE) loop 1
t1 (RUNNABLE) loop 2
t1 (TIMED_WAITING) is interrupted
t1 (RUNNABLE) catch InterruptedException
t1 (TERMINATED) is interrupted now

猜你喜欢

转载自blog.csdn.net/tanwenfang/article/details/92404061