首页 > 编程语言 > 详细

java线程condition

时间:2017-01-14 21:59:56      阅读:153      评论:0      收藏:0      [点我收藏+]

子线程先执行一段代码,再主线程再执行一段代码,两个线程都循环执行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

原文:http://www.cnblogs.com/zhouquan-1992-04-06/p/6286142.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!