java线程为什么弃用stop,suspend方法

为什么弃用stop方法?

1、在stop的时候不只是你这一个线程受影响,所有和这个线程相关的锁也会释放。这是从语言上说。从业务上说,我们辛辛苦苦在代码中做的异常检查,回滚等操作就形同虚设了。

2、随意砍掉一条业务线,后续差擦屁股的事会少么?


为什么弃用suspend?

如condition中的wait,notify等都是成双成对,suspend也是一样,有resume对应,为什么不弃用await和notify呢?因为condition在使用时线程一直属于运行状态,除非时间片分配到别的线程了。而一旦调用suspend,线程立马挂起,处于阻塞状态。任你的suspend和resume逻辑如何严谨,你能保证你在调用suspend的时候,resume不需要锁吗?resume需要的那个锁的释放会不会就在suspend后面的操作中?

所以,suspend就是一个不定时炸弹,自然得弃用。


参考文档:为什么弃用stop,suspend


3、join用法?

某些情况下,一个线程需要等待另外一个线程完成了才会接着执行。此时,用到join。


package com.example.demo.interrupt;

public class TestJoin {
	public static void main(String[] args) {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " start.");
		Thread1 t1 = new Thread1();
		Thread2 t2 = new Thread2(t1);
		try {
			t1.start();
			Thread.sleep(2000);
			t2.start();
			t2.join();
		} catch (Exception e) {
			System.out.println("exception from main");
		}
		System.out.println(threadName + " end.");
	}
}

class Thread1 extends Thread {
	public Thread1() {
		super("[Thread1] Thread");
	}

	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " start.");
		try {
			for (int i = 0; i < 5; i++) {
				System.out.println(threadName + " loop at " + i);
				Thread.sleep(1000);
			}
			System.out.println(threadName + " end.");
		} catch (Exception e) {
			System.out.println("exception from " + threadName + ".run");
		}

	}
}

class Thread2 extends Thread {
	Thread1 t1;

	public Thread2(Thread1 thread1) {
		super("[Thread2] Thread");
		this.t1 = thread1;
	}

	public void run() {
		String threadName = Thread.currentThread().getName();
		System.out.println(threadName + " start.");
		try {
			t1.join();
			System.out.println(threadName + " end.");
		} catch (Exception e) {
			System.out.println("exception from" + threadName + ".run");
		}

	}
}

结果为:

main start.
[Thread1] Thread start.
[Thread1] Thread loop at 0
[Thread1] Thread loop at 1
[Thread2] Thread start.
[Thread1] Thread loop at 2
[Thread1] Thread loop at 3
[Thread1] Thread loop at 4
[Thread1] Thread end.
[Thread2] Thread end.
main end


4、yield用法?

yield就是把时间片使用权让给另外的线程。即便本线程比另外线程的优先级高,也可以把时间片让给对方。


参考资料:join和yield的使用







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值