暂停线程意味着线程还可以恢复运行
package resumeSuspend; /** * Created by liping.sang on 2017/1/13 0013. */ public class MyThread extends Thread{ private long i=0; public void run(){ while(true){ i++; } } public long getI() { return i; } public void setI(long i) { this.i = i; } }
package resumeSuspend; import interruptedAndIsInterrupted.*; /** * Created by Administrator on 2017/1/13 0013. */ public class Run { public static void main(String [] args){ try { MyThread thread = new MyThread(); 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("B"+System.currentTimeMillis()+" i="+thread.getI()); Thread.sleep(5000); System.out.println("B"+System.currentTimeMillis()+" i="+thread.getI()); }catch (Exception e){ } } }
A1484293047430 i=3313762423 A1484293052430 i=3313762423 B1484293057430 i=6671460667 B1484293062430 i=6671460667
从执行结果来看,线程的确被暂停了,而且还可以恢复成运行的状态。
使用suspend和resume方法时,如果使用不当,极易造成公共的同步对象的独占,使得其他线程无法访问公共同步对象。
suspend和resume方法的缺点---不同步
使用suspend和resume方法时也容易出现因为线程的暂停二导致数据不同步的情况
看如下例子:
package suspend_resume_mosamevalue; /** * Created by liping.sang on 2017/1/13 0013. */ 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); } }
package suspend_resume_mosamevalue; /** * Created by liping.sang on 2017/1/13 0013. */ public class Run { public static void main(String [] args) throws InterruptedException { final MyObject myobject = new MyObject(); Thread thread1=new Thread(){ public void run(){ myobject.setValue("a","aa"); } }; thread1.setName("a"); thread1.start(); Thread.sleep(500); Thread thread2 = new Thread(){ public void run(){ myobject.printUsernamePassword(); } }; thread2.start(); } }
停止a线程
a 11
可以看出运行的结果出现了值不同步的情况。