如果用suspend()方法将线程挂起,线程占有的资源不会被释放,很有可能让其他线程死锁。
package Suspend;
public class SuspendDemo implements Runnable {
private static Object obj = new Object();
@Override
public void run() {
synchronized (obj) {
System.out.println(Thread.currentThread().getName() + "占有资源");
Thread.currentThread().suspend();
}
System.out.println(Thread.currentThread().getName() + "释放资源");
}
public static void main(String[] a) throws InterruptedException {
Thread t1=new Thread(new SuspendDemo(),"t1");
Thread t2=new Thread(new SuspendDemo(),"t2");
t1.start();
Thread.sleep(1000);
t2.start();
t1.resume();
Thread.sleep(1000);
t2.resume();
}
}
t1不会释放资源
如果代码这样写,将会导致t2死锁
package Suspend;
public class SuspendDemo implements Runnable {
private static Object obj = new Object();
@Override
public void run() {
synchronized (obj) {
System.out.println(Thread.currentThread().getName() + "占有资源");
Thread.currentThread().suspend();
}
System.out.println(Thread.currentThread().getName() + "释放资源");
}
public static void main(String[] a) throws InterruptedException {
Thread t1=new Thread(new SuspendDemo(),"t1");
Thread t2=new Thread(new SuspendDemo(),"t2");
t1.start();
Thread.sleep(1000);
t2.start();
t1.resume();
// Thread.sleep(1000);
t2.resume();
}
}
因为在执行中不能控制run()方法里的代码和t2.start()方法后面的代码执行顺序,如果t2先执行了resume()方法,再去执行run()方法中的suspend()方法那么就会死锁。