java resume是什么?讓我們一起來了解一下吧!
java resume是java中與線程API有關的方法。resume方法是可以執行恢復線程,其他還有兩種方法stop和suspend,它們分別負責終止執行線程和暫停執行線程。
?
在java程序中,suspend() 和 resume() 兩個方法結合應用,suspend()會使線程進入阻塞情況,并且沒有自動恢復功能,所以必須其對應的 resume() 被調用,才可以讓線程重新進入可執行狀態。
suspend() 和 resume() 方法有很多不足之處,比如:
1.如果 suspend() 和 resume() 方法操作不當時很容易造成公共同步對象的獨占,使其他線程不能去訪問公共對象資源。
2.當 suspend() 和 resume() 方法使用不當時也容易造成數據不同步的情況。
實戰演練,具體步驟如下:
package?com.rhwayfun.concurrency; ? import?java.text.DateFormat; import?java.text.SimpleDateFormat; import?java.util.Date; import?java.util.concurrent.TimeUnit; ? /** ?*?Created?by?rhwayfun?on?16-4-2. ?*/ public?class?DeprecatedThreadMethod?{ ? ????public?static?void?main(String[]?args)?throws?InterruptedException?{ ????????DateFormat?format?=?new?SimpleDateFormat("HH:mm:ss"); ????????Thread?printThread?=?new?Thread(new?Runner(),"PrintThread"); ????????//設為守護線程 ????????printThread.setDaemon(true); ????????//開始執行 ????????printThread.start(); ????????//休眠3秒,也就是PrintThread運行了3秒 ????????TimeUnit.SECONDS.sleep(3); ????????//嘗試暫停 ????????printThread.suspend(); ????????System.out.println("main?thread?suspend?PrintThread?at?"?+?format.format(new?Date())); ????????TimeUnit.SECONDS.sleep(3); ????????//將PrintThread進行恢復,繼續輸出內容 ????????printThread.resume(); ????????System.out.println("main?thread?resume?PrintThread?at?"?+?format.format(new?Date())); ????????TimeUnit.SECONDS.sleep(3); ????????//嘗試終止PrintThread,停止輸出內容 ????????printThread.stop(); ????????System.out.println("main?thread?stop?PrintThread?at?"?+?format.format(new?Date())); ????????TimeUnit.SECONDS.sleep(3); ????} ? ????/** ?????*?該任務實現每隔一秒打印信息 ?????*/ ????static?class?Runner?implements?Runnable{ ????????public?void?run()?{ ????????????DateFormat?format?=?new?SimpleDateFormat("HH:mm:ss"); ????????????while?(true){ ????????????????System.out.println(Thread.currentThread().getName()?+?"?run?at?"?+?format.format(new?Date())); ????????????????//休眠一秒后繼續打印 ????????????????SleepUtil.second(1); ????????????} ????????} ????} }
以上就是小編今天的分享了,希望可以幫助到大家。