在本例中,使用了线程锁Lock和条件变量Condition,线程Lock可以保证一个时间内一个线程先做完自己的事务,另外一个线程才能执行自己事务。
加上条件变量Condition后,线程之间就可以相互通信,也就是说,一个线程可以使用condition.signal();发出信号量,说本线程的工作已经做完了,
那么另外一个线程也通过条件变量的监听(condition.await();)的线程,就可以得知这一信号。这样应用条件变量的线程间就可以很好的通讯了。
package three.day.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionTest {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
final Business2 business = new Business2();
service.execute(new Runnable(){
public void run() {
for(int i=0;i<50;i++){
business.sub();
}
}
});
for(int i=0;i<50;i++){
business.main();
}
service.shutdown();
}
}
class Business2{
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
boolean bShouldSub = true;
public void sub(){
lock.lock();
if(!bShouldSub)
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try
{
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName() + " : " + i);
}
bShouldSub = false;
condition.signal();
}finally{
lock.unlock();
}
}
public void main(){
lock.lock();
if(bShouldSub)
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try
{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + " : " + i);
}
bShouldSub = true;
condition.signal();
}finally{
lock.unlock();
}
}
}