java线程condition

Posted 风的低吟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Java并发多线程编程——锁绑定多个条件Condition示例

java多线程,多线程加锁以及Condition类的使用

线程高级篇-Lock锁和Condition条件

java多线程-Condition

java线程的共享变量

Java多线程通信syncrhoized下wait()/notify()与ReentrantLock下condition的用法比较