search
HomeJavajavaTutorialJava multi-threaded readwritelock example of separation of reading and writing

This article mainly introduces the relevant content of readwritelock separation of Java multi-threading. The article involves specific example codes, which has certain reference value. Friends who need it can learn about it.

In multi-threaded development, there is often a situation where we want toseparate reading and writing. For the reading action, multiple threads can read the resource at the same time, but for the writing action, only one thread can operate at the same time, and at the same time, when there is a writing thread operating this When accessing a resource, other reading threads cannot operate this resource. This greatly maximizes the characteristics of multi-threading and can fully utilize the capabilities of multi-threading.

In Java, the ReadWriteLock interface realizes this requirement for us. Through its implementation class ReentrantReadWriteLock, we can easily achieve the effect just now. Let's use an example to illustrate this class. usage.


package com.bird.concursey.charpet3; 
import java.util.concurrent.locks.ReadWriteLock; 
import java.util.concurrent.locks.ReentrantReadWriteLock; 
public class PricesInfo { 
  private double price1; 
  private double price2; 
  private ReadWriteLock lock; 
  public PricesInfo() { 
    price1 = 1.0; 
    price2 = 2.0; 
    lock = new ReentrantReadWriteLock(); 
  } 
  public double getPrice1() { 
    //读取资源锁定 
    lock.readLock().lock(); 
    double value = price1; 
    lock.readLock().unlock(); 
    return value; 
  } 
  public double getPrice2() { 
    lock.readLock().lock(); 
    double value = price2; 
    lock.readLock().unlock(); 
    return value; 
  } 
  public void setPrices(double price1, double price2) { 
    lock.writeLock().lock(); 
    this.price1 = price1; 
    this.price2 = price2; 
    lock.writeLock().unlock(); 
  } 
}

The following are two different classes for reading and writing


package com.bird.concursey.charpet3; 
public class Reader implements Runnable { 
  private PricesInfo pricesInfo; 
  public Reader(PricesInfo pricesInfo) { 
    this.pricesInfo = pricesInfo; 
  } 
  @Override 
  public void run() { 
    for (int i = 0; i < 10; i++) { 
      System.out.printf("%s: Price 1: %f\n", Thread.currentThread() 
          .getName(), pricesInfo.getPrice1()); 
      System.out.printf("%s: Price 2: %f\n", Thread.currentThread() 
          .getName(), pricesInfo.getPrice2()); 
    } 
  } 
}


package com.bird.concursey.charpet3; 
public class Writer implements Runnable { 
  private PricesInfo pricesInfo; 
  public Writer(PricesInfo pricesInfo) { 
    this.pricesInfo = pricesInfo; 
  } 
  @Override 
  public void run() { 
    for (int i = 0; i < 3; i++) { 
      System.out.printf("Writer: Attempt to modify the prices.\n"); 
      pricesInfo.setPrices(Math.random() * 10, Math.random( ) * 8); 
      System.out.printf("Writer: Prices have been modified.\n"); 
      try { 
        Thread.sleep(2); 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } 
    } 
  } 
  public static void main(String[] args) { 
    PricesInfo pricesInfo = new PricesInfo(); 
    Reader readers[] = new Reader[5]; 
    Thread threadsReader[] = new Thread[5]; 
    for (int i = 0; i < 5; i++){ 
      readers[i] = new Reader(pricesInfo); 
      threadsReader[i] = new Thread(readers[i]); 
    } 
    Writer writer = new Writer(pricesInfo); 
    Thread threadWriter = new Thread(writer); 
    for (int i = 0; i < 5; i++){ 
      threadsReader[i].start(); 
    } 
    threadWriter.start(); 
  } 
}

Summarize

The above is the detailed content of Java multi-threaded readwritelock example of separation of reading and writing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function