Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
线程顺序执行
package cn.deepmax.lang.test.time.lang.thread;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class MultiConditionTest {
private int size;
private int total;
private ReentrantLock lock;
private Condition[] conditions;
private Task[] tasks;
private volatile int now;
private volatile boolean started;
private CountDownLatch latch;
public MultiConditionTest(int threadSize, int total) {
this.size = threadSize;
this.total = total;
lock = new ReentrantLock();
now = 0;
latch = new CountDownLatch(threadSize);
init();
}
void init(){
conditions = new Condition[size];
tasks = new Task[size];
for (int i = 0; i < size; i++) {
conditions[i] = lock.newCondition();
}
for (int i = 0; i < size - 1; i++) {
tasks[i] = new Task(i, conditions[i], conditions[i+1]);
}
tasks[size-1] = new Task(size-1, conditions[size-1], conditions[0]);
}
void start(){
for (int i = 0; i < size; i++) {
tasks[i].start();
}
try {
latch.await();
started=true;
lock.lock();
conditions[0].signal();
} catch (InterruptedException e) {
//ingore
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
MultiConditionTest test = new MultiConditionTest(10,100);
test.start();
}
static void print(Object obj){
System.out.println("["+Thread.currentThread().getName()+"]"+obj.toString());
}
private class Task{
int id;
Thread thread;
Condition startCondition;
Condition endCondition;
public Task(int id, Condition startCondition, Condition endCondition) {
this.id = id;
this.startCondition = startCondition;
this.endCondition = endCondition;
}
void start(){
thread = new Thread(getTask());
thread.setName("Thread-\t"+id);
thread.start();
}
Runnable getTask(){
return ()->{
try{
lock.lock();
while(now<=total){
while (!started){
latch.countDown();
startCondition.await();
}
if(now % size!=id){
startCondition.await();
}else{
print(now);
now++;
endCondition.signal();
}
}
endCondition.signal();
} catch (InterruptedException e) {
//ignore
} finally {
lock.unlock();
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment