suspend方法的缺点一:
该方法很容易造成公共的同步对象的独占,使得其他线程无法访问公共同步对象。
public class Run {
public static void main(String[] args){
try{
final SynchronizedObject2 object = new SynchronizedObject2();
Thread thread1 = new Thread(){
@Override
public void run(){
object.printString();
}
};
thread1.setName("a");
thread1.start();
Thread.sleep(1000);
Thread thread2 = new Thread(){
@Override
public void run(){
System.out.println("thread2启动了,但进入不了printString()方法! 只打印了1个begin ");
System.out.println(" 因为printString()方法被a线程锁定并且永远suspend暂停了! ");
object.printString();
}
};
thread2.start();
}catch(InterruptedException e){
e.printStackTrace();
}
}
public static void main1(String[] args){
try {
MyThread12 thread = new MyThread12();
thread.start();
Thread.sleep(5000);
// A段
thread.suspend();
System.out.println("A="+System.currentTimeMillis()+" i="+thread.getI());
Thread.sleep(5000);
System.out.println("A="+System.currentTimeMillis()+" i="+thread.getI());
// B段
thread.resume();
Thread.sleep(5000);
// C段
thread.suspend();
System.out.println("A="+System.currentTimeMillis()+" i="+thread.getI());
Thread.sleep(5000);
System.out.println("A="+System.currentTimeMillis()+" i="+thread.getI());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class SynchronizedObject2 {
synchronized public void printString(){
System.out.println("begin");
if(Thread.currentThread().getName().equals("a")){
System.out.println("a 线程永远 suspend了 !");
Thread.currentThread().suspend();
}
System.out.println("end");
}
}
suspend方法的缺点二:
可能会出现线程的暂停,导致数据不同步
public class Run2 {
public static void main(String[] args){
try{
final MyObject object = new MyObject();
Thread thread1 = new Thread(){
@Override
public void run(){
object.setValue("a", "aa");
}
};
thread1.setName("a");
thread1.start();
Thread.sleep(500);
Thread thread2 = new Thread(){
@Override
public void run(){
object.printUsernamePassword();
}
};
thread2.start();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class MyObject {
private String username = "1";
private String password = "11";
public void setValue(String u, String p){
this.username = u;
if(Thread.currentThread().getName().equals("a")){
System.out.println("停止a线程");
Thread.currentThread().suspend();
}
this.password = p;
}
public void printUsernamePassword(){
System.out.println(username + " " + password);
}
}