---------------------- android培訓、java培訓、期待與您交流! ---------------------
工具類簡介
1. 如果需要在兩條線程間進行更多的信息交互,可以使用管道流。管道流有3種形式存在,即:PipedInputStream、PipedOutputStream、PipedWriter、PipedReader、Pipe.SinkChannel和Pipe.SourceChannel。具體參見《java瘋狂講義》16.6.3。
2. Semaphore可以維護當前訪問自身的線程個數,並提供了同步機制。使用Semaphore可以控制同時訪問資源的線程個數,例如,實現一個文件允許的併發訪問數。
示例代碼:
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Semaphore sp = new Semaphore(3);
for(int i=0;i<10;i++){
Runnable runnable = new Runnable(){
public void run(){
try {
sp.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("線程" + Thread.currentThread().getName() +
"進入,當前已有" + (3-sp.availablePermits()) + "個併發");
try {
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("線程" + Thread.currentThread().getName() + "即將離開");
sp.release();
//下面代碼有時候執行不準確,因爲其沒有和上面的代碼合成原子單元
System.out.println("線程" + Thread.currentThread().getName() +
"已離開,當前已有" + (3-sp.availablePermits()) + "個併發"); }};
service.execute(runnable);
}
}}
3. CyclicBarrier
表示大家彼此等待,大家集合好後纔開始出發,分散活動後又在指定地點集合碰面,這就好比整個公司的人員利用週末時間集體郊遊一樣,先各自從家出發到公司集合後,再同時出發到公園遊玩,在指定地點集合後再同時開始就餐,…。
代碼示例:
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CyclicBarrier cb = new CyclicBarrier(3);
for(int i=0;i<3;i++){
Runnable runnable = new Runnable(){
public void run(){
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點1,當前已有" + cb.getNumberWaiting() + "個已經到達,正在等候");
cb.await();
Thread.sleep((long)(Math.random()*10000));
System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點2,當前已有" + cb.getNumberWaiting() + "個已經到達,正在等候");
cb.await();
Thread.sleep((long)(Math.random()*10000));
System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點3,當前已有" + cb.getNumberWaiting() + "個已經到達,正在等候");
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
service.shutdown();
}
}
4. CountDownLatch
猶如倒計時計數器,調用CountDownLatch對象的countDown方法就將計數器減1,當計數到達0時,則所有等待者或單個等待者開始執行。
可以實現一個人(也可以是多個人)等待其他所有人都來通知他,這猶如一個計劃需要多個領導都簽字後才能繼續向下實施。還可以實現一個人通知多個人的效果,類似裁判一聲口令,運動員同時開始奔跑。用這個功能做百米賽跑的遊戲程序不錯哦!
代碼示例:
public class CountdownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for(int i=0;i<3;i++){
Runnable runnable = new Runnable(){
public void run(){
try {
System.out.println("線程" + Thread.currentThread().getName() + "正準備接受命令");
cdOrder.await();
System.out.println("線程" + Thread.currentThread().getName() + "已接受命令");
Thread.sleep((long)(Math.random()*10000));
System.out.println("線程" + Thread.currentThread().getName() + "迴應命令處理結果");
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println("線程" + Thread.currentThread().getName() + "即將發佈命令");
cdOrder.countDown();
System.out.println("線程" + Thread.currentThread().getName() + "已發送命令,正在等待結果");
cdAnswer.await();
System.out.println("線程" + Thread.currentThread().getName() + "已收到所有響應結果");
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}
5. Exchanger
用於實現兩個人之間的數據交換,每個人在完成一定的事務後想與對方交換數據,第一個先拿出數據的人將一直等待第二個人拿着數據到來時,才能彼此交換數據。
代碼示例:
public class ExchangerTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Exchanger exchanger = new Exchanger();
service.execute(new Runnable(){
public void run() {
try {
Thread.sleep((long)(Math.random()*10000));
String data1 = "zxx";
System.out.println("線程" + Thread.currentThread().getName() + "正在把數據" + data1 +"換出去");
String data2 = (String)exchanger.exchange(data1);
System.out.println("線程" +
Thread.currentThread().getName() + "換回的數據爲" + data2);
}catch(Exception e){
}
}
});
service.execute(new Runnable(){
public void run() {
try {
Thread.sleep((long)(Math.random()*10000));
String data1 = "lhm";
System.out.println("線程" + Thread.currentThread().getName() + "正在把數據" + data1 +"換出去");
String data2 = (String)exchanger.exchange(data1);
System.out.println("線程" + Thread.currentThread().getName() + "換回的數據爲" + data2);
}catch(Exception e){
}
}
});
}
}
注:以上工具類在張孝祥老師的基礎加強中有簡單講解。具體詳見API。
--------------------- android培訓、java培訓、期待與您交流! ----------------------