挂起(suspend)和继续执行(resume)线程
– suspend()不会释放锁
– 如果加锁发生在resume()之前 ,则死锁发生
测试代码:
/**
*
* @ClassName: TestThread
* @Description:挂起(suspend)和继续执行(resume)线程
* @author: He LongYun
* @date: 2019年1月31日 下午1:38:47
*/
public class TestThread {
public static Object obj = new Object();
static SuspendThread t1 = new SuspendThread("t1");
static SuspendThread t2 = new SuspendThread("t2");
public static class SuspendThread extends Thread {
public SuspendThread(String name) {
super.setName(name);
}
@Override
public void run() {
synchronized (obj) {
System.out.println("开始 ----->" + getName());
Thread.currentThread().suspend();
}
}
}
public static void main(String[] args) throws InterruptedException {
/**
* t1 结束 t2 没有结束
* t1调用resume()时候,t1已经调用suspend()方法 ,再调用join(),t1挂起结束
* t2在先调用join()后调用suspend(),t2挂起后不能结束,形成死锁
*/
//开启线程t1
t1.start();
//暂停1秒钟,让t1挂起
Thread.sleep(1000);
//开启线程t2
t2.start();
//t1继续执行
t1.resume();
//t2继续执行
t2.resume();
//t1等待线程结束
t1.join();
//t2等待线程结束
t2.join();
}
}