首页 > 代码库 > java线程condition
java线程condition
子线程先执行一段代码,再主线程再执行一段代码,两个线程都循环执行50遍。用2个condition来实现,一个是子线程的condition,一个是主线程的condition,代码如下:
package threadLock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionCommunication { public static void main(String[] args) { final Bussiness bus = new Bussiness(); //子线程开启 new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 50; ++i) { bus.sub(); } } }).start(); //主线程开启 for (int i = 0; i < 50; ++i) { bus.MAIN(); } } } class Bussiness { private boolean subShouldAble = true; private Lock lock = new ReentrantLock(); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); public void sub() { lock.lock(); //上锁,防止主线程执行 if (!subShouldAble) {//如果不是子线程执行,则子线程等待 try { condition1.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < 10; j++) { System.out.println("sub squence is :" + j); } subShouldAble = false; condition2.signal(); //唤醒主线程执行 lock.unlock(); //解锁 } public void MAIN() { lock.lock(); //上锁,防止子线程执行 while (subShouldAble) { //如果是子线程执行,则主线程等待 try { condition2.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < 30; j++) { System.out.println("main squence is :" + j); } subShouldAble = true; condition1.signal(); //唤醒主线程 lock.unlock(); //解锁 } }
java线程condition
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。