日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

线程:suspend与resume方法

發布時間:2025/6/15 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程:suspend与resume方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

suspend方法的缺點一:?

? ?該方法很容易造成公共的同步對象的獨占,使得其他線程無法訪問公共同步對象。

? ??

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啟動了,但進入不了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(){@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);} }

?

?

總結

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

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。