标签:io ar java for sp on art bs ad
package com.xsz.demo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 兩個線程交替執行
* @author cwqi
*/
public class AdvanceMutiThread {
public static void main(String[] args) {
final ThreadTest5 threadTest5 = new ThreadTest5();
final int count = 5;
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < count; i++) {
threadTest5.addMethod();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < count; i++) {
threadTest5.subtractMethod();
}
}
}).start();
}
}
class ThreadTest5 {
private Lock lock = new ReentrantLock();
private int cons = 0;
int flag = 0;
Condition con1 = lock.newCondition();
Condition con2 = lock.newCondition();
public void addMethod() {
// 執行加1
lock.lock();
try {
while (flag % 2 != 0)
con1.await();
System.out.println("Thread A: " + (++cons));
flag++;
con2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void subtractMethod() {
// 執行減1
lock.lock();
try {
while (flag % 2 == 0)
con2.await();
System.out.println("Thread B: " + (--cons));
flag++;
con1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
标签:io ar java for sp on art bs ad
原文地址:http://my.oschina.net/u/1861837/blog/341013