public class SortedPrintMore extends Thread{
//由于是不同的Thread n最好是共享
//无锁化
int i;
static int n;
static Lock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public SortedPrintMore(int n) {
this.i = n;
}
//使用lock和condition
@Override
public void run() {
while(true){
if(n %3 == i){
//抢到锁了
if(n>100) return;
lock.lock();
System.out.println(Thread.currentThread().getName()+" : "+n++);
try {
condition.signalAll();
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
}
}
}
public static void main(String[] args) {
SortedPrintMore more1 = new SortedPrintMore(0);
SortedPrintMore more2 = new SortedPrintMore(1);
SortedPrintMore more3 = new SortedPrintMore(2);
more1.start();
more2.start();
more3.start();
}
}
按序打印_lock和condition
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:51_n皇后
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Java并发Lock和Condition
文章目录一.简介二.原理2.1 管程2.2 可见性2.3 可重入锁2.4 公平锁与非公平锁2.5 用锁的
java 并发编程 多线程 公平锁 加锁 -
Lock和Condition
1 什么是可重入锁 可重入锁是说一个线程在已经获取了该锁的情况下
java 公平锁 重入锁 参考资料 生产者消费者