1.runnable是thread執行的邏輯示例**:2.callablefuturetask也是thread要執行的邏輯,只是封裝了獲取結果的功能
因此: 啟動執行緒的方式只有一種: new thread().start();
public class demo_stop
// 輸出結果
thread.print();
}}class mythread extends thread catch (interruptedexception e)
++j;
}system.out.println("鎖釋放。。。");
}public void print()
}
列印結果:
需要的輸出結果應該是i=0 j=0;
stop方法沒***同步**看塊中的資料一致性, 出現了執行緒安全問題
示例**:
public static void main(string args) throws interruptedexception catch (interruptedexception e) }}
});workthread.start();
thread.sleep(3000l);
workthread.interrupt();
}
注意點:
1.interrupt方法並不會中斷執行緒,只是打上了中斷標記示例**:
public static void main(string args) throws interruptedexception }};
testthread.start();
thread.sleep(2000);
//呼叫interrupt方法,不會改變執行緒狀態
//並不會讓執行緒退出,只是做了乙個interrupt標記
testthread.interrupt();
}
輸出結果:
可以看到,在sleep2秒後,isinterrupted的狀態值由false變為了true
2.如果該執行緒在呼叫 wait(),wait(long)方法,join() 、 join(long, int) 、join(long, int)、sleep(long, int)或sleep(long, int)等方法後,處於waiting、timed waiting狀態時,在該執行緒被呼叫interrupt方法後,執行緒的waiting、timed waiting狀態將被清除,並丟擲interruptedexception異常。示例**:
public static void main(string args) throws interruptedexception catch (interruptedexception e) }}
};testthread.start();
thread.sleep(1000);
testthread.interrupt();
}
列印結果:
3.如果目標執行緒是被i/o 或者nio中的channel所阻塞,同樣,i/o操作會被中斷或者返回特殊異常值。
4.park()\parknanos方法執行後,執行緒也處於 waiting、timed waiting,也會被喚醒,但是不會拋異常,且有很詭異的情況發生。示例**:
public static void main(string args) throws interruptedexception
}});
testthread.start();
thread.sleep(1000l);
testthread.interrupt();
system.out.println("**********==end*************************====");
}
列印結果
定義:
守護執行緒注意點:是指在程式執行的時候在後台提供一種通用服務的執行緒,
程序結束時,會殺死所有守護執行緒。
1.在daemon執行緒中產生的新執行緒也是daemon的作用:2.不能把正在執行的常規執行緒設定為守護執行緒,thread.setdaemon(true)必須在thread.start()之前設定,否則會跑出乙個illegalthreadstateexception異常。
3.守護執行緒它會在任何時候甚至在乙個操作的中間發生中斷,因此應該永遠不去訪問固有資源,如檔案、資料庫等等
countdownlatch可以使乙個執行緒等待其他執行緒各自執行完畢後再執行。示例**:
public class demo_countdownlatch
ctl.countdown();
}}.start();
}//設定開關,設定門栓
ctl.await();
system.out.println(num.get());}}
作用:
常用於限制可以訪問某些資源(物理或邏輯的)執行緒數目。示例**:是一種用來控制併發量的共享鎖。
public class demo_semaphore catch (interruptedexception e)
//模擬db查詢
querydb("localhost:3306");
sp.release();
}}.start();}}
//傳送乙個http請求
public static void querydb(string uri)
}
作用:
可以迴圈利用的屏障示例**:
public class demo_cyclicbarrier
});//傳入乙個runnable,列印柵欄
for (int i=0; i< 100; i++) catch (interruptedexception e) catch (brokenbarrierexception e)
}}.start();
locksupport.parknanos(1000 * 1000 * 1000l);}}
}
多執行緒之執行緒的中止
1 安全中止執行緒 安全中止執行緒有以下兩種方法 1.1 執行緒函式返回 直接使用return語句。1.2 呼叫afxendthread函式 函式定義如下 void afxendthread uint nexitcode 引數nexitcode為執行緒的退出碼。執行緒0 setevent m pth...
c 多執行緒 中止前清理
gcc lpthread std c99 o main main.c deepfuture deepfuture laptop mytest main 1chen1 2chen2 3chen6 4chen24 5chen120 6chen720 7chen5040 8chen40320 9chen3...
多執行緒之執行緒同步
pulse lockobj 表示釋放當前被lock的lockobj,容許其他執行緒呼叫。相當於暫時掛起當前執行緒 wait lockobj 表示等待當前被其他執行緒占用的lockobj。下面的 將會交替執行兩個執行緒 class ticktock console.write tick monitor...