suspend与resume是一对暂停和唤醒的方法。
1.使用suspend不当会造成公共的同步对象的独占,例:
public static class CommonObject{
synchronized public void printString(){
if(Thread.currentThread().getName().equals("a")){
System.out.println("当前为线程a,并且suspend a线程了");
Thread.currentThread().suspend();
}else{
System.out.println("其他线程");
}
}
}
public static void main(String[] args) throws InterruptedException {
final CommonObject commonObject = new CommonObject();
new Thread("a"){
@Override
public void run() {
commonObject.printString();
};
}.start();
Thread.sleep(500);
new Thread("b"){
@Override
public void run() {
commonObject.printString();
};
}.start();
}
结果:
当前为线程a,并且suspend a线程了
输出分析:可以得知线程a在公共对象的同步方法中使用suspend,导致公共对象commonObject的 printString方法被a独占。致使b线程无法使用printString方法,直到a线程执行完printString
2.可能造成不同步例:
public static class CommonObject{
private String name = "无";
private int age = -1;
synchronized public void setProperty(String name,int age){
this.name = name;
if(Thread.currentThread().getName().equals("a")){
Thread.currentThread().suspend();
}
this.age = age;
}
public void printProperty(){
System.out.println("name= "+name+" age= "+age);
}
}
public static void main(String[] args) throws InterruptedException {
final CommonObject commonObject = new CommonObject();
new Thread("a"){
@Override
public void run() {
commonObject.setProperty("张三",25);
};
}.start();
Thread.sleep(100);
commonObject.printProperty();
}
name= 张三 age= -1
输出分析:线程a在设置属性过程中中断了,导致"年龄"属性没有设置,结果在main方法中就看到对象不同步