不定数量多线程轮询打印i++
程序员文章站
2024-03-12 20:06:14
...
package dmeo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
private static Lock lock = new ReentrantLock();
static List<Condition> conditions;
private static int count = 0;
private static int lockNumber1=0;
static void init(int lockNumber) throws InterruptedException {
lockNumber1=lockNumber;
conditions=new ArrayList<>(lockNumber);
Condition condition;
//细粒度的condition
for(int i=0;i<lockNumber;i++) {
condition=lock.newCondition();
conditions.add(condition);
}
//启动所有线程
for(int i=0;i<lockNumber;i++) {
new ThreadA(i).start();
}
}
static class ThreadA extends Thread {
//把自己在condition中的位置记住
private int i;
public ThreadA(int i) {
this.i=i;
}
@Override
public void run() {
try {
lock.lock();
while(count<99) {
while (count % lockNumber1 != i){
conditions.get(i).await();; //锁住自己
}
if(count > 100 ) break;
System.out.println(Thread.currentThread().getId()+":"+count++);
//如果是最后一个线程,就唤醒第一个.
//直接唤醒下一个线程
if(i != lockNumber1-1) {
conditions.get(i+1).signal();
}
else {
conditions.get(0).signal();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
init(3);
}
}
上一篇: Apache Hive 1.2.0 release
下一篇: Scala趣味题之空心菱形
推荐阅读