⑴ 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了。