首页 > 代码库 > 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