为什么弃用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的使用