JAVA中怎么使用Lock与Condition实现排它同步通信

这篇文章将为大家详细讲解有关JAVA中怎么使用Lock与Condition实现排它同步通信,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创新互联公司专注于铜鼓网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供铜鼓营销型网站建设,铜鼓网站制作、铜鼓网页设计、铜鼓网站官网定制、微信小程序定制开发服务,打造铜鼓网络公司原创品牌,更为您提供铜鼓网站排名全网营销落地服务。

package com.study;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo {

  public static void main(String[] args) {
    Demo demo = new Demo();
    final OutPutClass putPutClass = demo.new OutPutClass();
    Thread thread = new Thread(new Runnable() {

      @Override
      public void run() {
        while (true) {
          putPutClass.ins();
        }
      }
    });
    thread.start();

    Thread thread2 = new Thread(new Runnable() {

      @Override
      public void run() {
        while (true) {
          putPutClass.des();
        }
      }
    });
    thread2.start();
  }

  class OutPutClass {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    private boolean isSync = true;

    public void ins() {
      lock.lock();
      try {
        while (!isSync) {
          condition.await();
        }
        Thread.sleep(1000L);
        System.out.println("正在上传中....");
        isSync = false;
        condition.signal();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }

    public void des() {
      lock.lock();
      try {
        while (isSync) {
          condition.await();
          Thread.sleep(1000L);
        }
        System.out.println("下载结束....");
        isSync = true;
        condition.signal();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally{
        lock.unlock();
      }
    }
  }
}

关于JAVA中怎么使用Lock与Condition实现排它同步通信就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


文章题目:JAVA中怎么使用Lock与Condition实现排它同步通信
本文网址:http://lszwz.com/article/jpjege.html

其他资讯

售后响应及时

7×24小时客服热线

数据备份

更安全、更高效、更稳定

价格公道精准

项目经理精准报价不弄虚作假

合作无风险

重合同讲信誉,无效全额退款