導航:首頁 > 編程語言 > suspendjava

suspendjava

發布時間:2025-06-18 07:14:09

java suspend()的問題

suspend()該方法在jdk1.6中已經不推薦使用了,過時了。如果是非阻塞線程只加①句,「使用一個共享變數,線程周期性檢測這一變數的值」。如果線程被阻塞,它便不能核查共享變數,也就不能停止。因此不加①只加②即可實現。
class A extends Thread
{
volatile boolean stop = false;

static class B
{
public void () throws Exception
{
A thread = new A();
System.out.println("Starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Asking thread to stop...");
thread.stop = true; // ①
thread.interrupt(); // ②
Thread.sleep(3000);
System.out.println("Stopping application...");
// System.exit( 0 );
}
}

public void run()
{
while (!stop)
{
System.out.println("Thread running...");
try
{
Thread.sleep(1000); // 模擬線程被阻塞
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted...");
}
}
System.out.println("Thread exiting under request...");
}
}

⑵ java程序運行過程中如何暫停,恢復

java控製程序執行,使用的是Thread這個類,可以控製程序暫停或者休眠幾秒再執行。示例如下:

{

privatebooleansuspend=false;

privateStringcontrol="";//只是需要一個對象而已,這個對象沒有實際意義

publicvoidsetSuspend(booleansuspend){
if(!suspend){
synchronized(control){
control.notifyAll();
}
}
this.suspend=suspend;
}

publicbooleanisSuspend(){
returnthis.suspend;
}

publicvoidrun(){
while(true){
synchronized(control){
if(suspend){
try{
control.wait();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
this.runPersonelLogic();
}
}

();

publicstaticvoidmain(String[]args)throwsException{
MyThreadmyThread=newMyThread(){
protectedvoidrunPersonelLogic(){
System.out.println("myTheadisrunning");
}
};
myThread.start();
Thread.sleep(3000);
myThread.setSuspend(true);
System.out.println("myThreadhasstopped");
Thread.sleep(3000);
myThread.setSuspend(false);
}
}

⑶ 我愛學Java之Thread中stop,suspend,resume為什麼不安全

當調用stop()方法時會發生兩件事:
1.即刻停止run()方法中剩餘的全部工作,包括在catch或finally語句中,並拋出ThreadDeath異常(通常情況下此異常不需要顯示的捕獲),因此可能會導致一些清理性的工作的得不到完成,如文件資料庫等的關閉。
2.會立即釋放該線程所持有的所有的鎖,導致數據得不到同步的處理,出現數據不一致的問題。
suspend()和resume()必須要成對出現,否則非常容易發生死鎖。
因為suspend方法並不會釋放鎖,如果使用suspend的目標線程對一個重要的系統資源持有鎖,那麼沒任何線程可以使用這個資源直到要suspend的目標線程被resumed,如果一個線程在resume目標線程之前嘗試持有這個重要的系統資源鎖再去resume目標線程,這兩條線程就相互死鎖了,也就凍結線程。

⑷ Java多線程調試如何完成信息輸出處理

默認情況下,在調試多線程程序時,當遇到斷點時(breakpoint),當前線程暫停,而其它線程繼續運行,有些情況下,這是我們不想要看到的。比如下面的例子:

再調試多線程程序:

可以看到所有線程都Suspend了。

閱讀全文

與suspendjava相關的資料

熱點內容
比特幣病毒哪些文件 瀏覽:997
軟體版是什麼文件 瀏覽:923
微信公眾號群發數據怎麼統計的 瀏覽:814
poi大文件名 瀏覽:77
如何復制word中的圖表 瀏覽:13
駕車吸煙代碼 瀏覽:57
蘋果刪了文件能修復嗎 瀏覽:365
u盤占內存但不顯示文件 瀏覽:101
後綴aex文件用什麼方式打開 瀏覽:822
更新了微信沒了轉賬 瀏覽:115
安卓平板觸摸屏不能用 瀏覽:285
獲取appstore版本號 瀏覽:674
新建文件夾3韓國 瀏覽:158
如何找到原神文件 瀏覽:547
蘋果平板系統升級好嗎 瀏覽:788
天賦異稟哪裡看app 瀏覽:659
自學編程設計軟體哪個最好用 瀏覽:191
sql2008資料庫查看 瀏覽:366
哇噻app怎麼充vip 瀏覽:55
ubuntu的網卡配置文件 瀏覽:809

友情鏈接