日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

线程:suspend与resume方法

發(fā)布時(shí)間:2025/6/15 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程:suspend与resume方法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

suspend方法的缺點(diǎn)一:?

? ?該方法很容易造成公共的同步對(duì)象的獨(dú)占,使得其他線程無(wú)法訪問(wèn)公共同步對(duì)象。

? ??

public class Run {public static void main(String[] args){try{final SynchronizedObject2 object = new SynchronizedObject2();Thread thread1 = new Thread(){@Overridepublic void run(){object.printString();}};thread1.setName("a");thread1.start();Thread.sleep(1000);Thread thread2 = new Thread(){@Overridepublic void run(){System.out.println("thread2啟動(dòng)了,但進(jìn)入不了printString()方法! 只打印了1個(gè)begin ");System.out.println(" 因?yàn)閜rintString()方法被a線程鎖定并且永遠(yuǎn)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 線程永遠(yuǎn) suspend了 !");Thread.currentThread().suspend();}System.out.println("end");} }

suspend方法的缺點(diǎn)二:

? ?可能會(huì)出現(xiàn)線程的暫停,導(dǎo)致數(shù)據(jù)不同步

public class Run2 {public static void main(String[] args){try{final MyObject object = new MyObject();Thread thread1 = new Thread(){@Overridepublic void run(){object.setValue("a", "aa");}};thread1.setName("a");thread1.start();Thread.sleep(500);Thread thread2 = new Thread(){@Overridepublic 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);} }

?

?

總結(jié)

以上是生活随笔為你收集整理的线程:suspend与resume方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。