lock绑定多个condition
作者:互联网
import java.util.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main{
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
new Thread(()->{
sharedResource.print5();
},"A").start();
new Thread(()->{
sharedResource.print10();
},"B").start();
new Thread(()->{
sharedResource.print15();
},"C").start();
}
}
class SharedResource{
private int num=1;
private Lock lock=new ReentrantLock();
private Condition c1= lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
public void print5(){
lock.lock();
try{
while(num!=1){
c1.await();
}
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
num=2;
c2.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print10(){
lock.lock();
try{
while(num!=2){
c2.await();
}
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
num=3;
c3.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print15(){
lock.lock();
try{
while(num!=3){
c3.await();
}
for(int i=0;i<15;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
num=1;
c1.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
最后的效果是 A打印5次 B打印10次 C打印15次
标签:java,lock,绑定,private,Condition,import,new,condition 来源: https://www.cnblogs.com/swifties270/p/16418448.html