1. 程式人生 > >多執行緒之CountDownLatch

多執行緒之CountDownLatch

CountDownLatch是Jdk5包Concurrent下很實用的工具類之一,主要用來實現多個執行執行緒的排序,下面例子通過三種方式實現同一功能(本例子JDK5下通過)

package regbin.exa.thread.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CountDownLatchTest {
public void CountDownLatchExa() throws InterruptedException {
final CountDownLatch countDownBegin = new CountDownLatch(1);
final CountDownLatch countDownEnd = new CountDownLatch(2);
Thread threadA = new Thread() {
@Override
public void run() {
try {
countDownBegin.await();
System.out.println("threadA");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownEnd.countDown();
}
}
};
Thread threadB = new Thread() {
@Override
public void run() {
try {
countDownBegin.await();
System.out.println("threadB");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownEnd.countDown();
}

}
};
System.out.println("CountDownLatchExa-X");
threadA.start();
threadB.start();
countDownBegin.countDown();
countDownEnd.await();
System.out.println("CountDownLatchExa-Y");
}

public void waitNotifyExa() throws InterruptedException {
final Object object = new Object();
Thread threadA = new Thread() {
@Override
public void run() {
try {
synchronized (object) {
object.wait();
}
System.out.println("threadA");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread threadB = new Thread() {
@Override
public void run() {
try {
synchronized (object) {
object.wait();
}
System.out.println("threadB");
} catch (InterruptedException e) {
e.printStackTrace();
}

}
};
System.out.println("waitNotifyExa-X");
threadA.start();
threadB.start();
Thread.sleep(2000);//保證通知動作線上程啟動之後發出
synchronized (object) {
object.notifyAll();
}
System.out.println("waitNotifyExa-Y");
}

public void CurrentLockExa() throws InterruptedException {
final Lock lock = new ReentrantLock();
final Condition object = lock.newCondition();
Thread threadA = new Thread() {
@Override
public void run() {
lock.lock();
try {
object.await();
System.out.println("threadA");
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
};
Thread threadB = new Thread() {
@Override
public void run() {
lock.lock();
try {
object.await();
System.out.println("threadB");
} catch (InterruptedException e) {
} finally {
lock.unlock();
}

}
};
System.out.println("CurrentLockExa-X");
threadA.start();
threadB.start();
Thread.sleep(2000);//保證通知動作線上程啟動之後發出
lock.lock();
try {
object.signalAll();
} finally {
lock.unlock();
}
System.out.println("CurrentLockExa-Y");
}

public static void main(String[] args) throws InterruptedException {
CountDownLatchTest test = new CountDownLatchTest();
test.CountDownLatchExa();
test.waitNotifyExa();
test.CurrentLockExa();
}
}