##底层业务线数据隔离
要求:子线程循环跑30次,暂停,然后跑到主线程40次,接着子线程循环跑30次,暂停,主线程跑40次
如此往复,一共交替50次
public class ThreadTest {
private static Lock lock = new ReentrantLock();
private static Condition chil_condition = lock.newCondition();
private static Condition main_condition = lock.newCondition();
private volatile static int sign = 0;
public static void main(String[] args) throws Exception{
new Thread(()->{
while (true){
for(int i = 0;i<50;i++){
lock.lock();
try {
if(sign!=0){
chil_condition.await();
}
for(int j = 0;j<30;j++){
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("子线程运行第%d轮第%d次",i,j));
}
sign=1;
main_condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}).start();
while (true){
for(int i = 0;i<50;i++){
lock.lock();
if(sign==0){
main_condition.await();
}
for(int j = 0;j<40;j++){
Thread.sleep(40);
System.out.println(String.format("主线程运行第%d轮第%d次",i,j));
}
sign=0;
chil_condition.signal();
lock.unlock();
}
}
}
}