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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值