The Lockers class is used to lock multithreaded Shared resources in Java multithreading concurrency

  • 2020-04-01 02:48:39
  • OfStack


package com.yao;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Lockers {

 
 public static class LockTest {
  Lock lock = new ReentrantLock();//The lock
  double value = 0d; //value
  int addtimes = 0;
  
  public void addValue(double v) {
   lock.lock();//In the lock
   System.out.println("LockTest to addValue: " + v + "   "
     + System.currentTimeMillis());
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
   }
   this.value += v;
   this.addtimes++;
   lock.unlock();//Release the lock
  }
  public double getValue() {
   return this.value;
  }
 }
 public static void testLockTest() throws Exception{
  final LockTest lockTest = new LockTest();
  //Create task 1 and call the addValue method of lockTest
  Runnable task1 = new Runnable(){
   public void run(){
    lockTest.addValue(55.55);
   }
  };
  //Create task 2 and call the getValue method of lockTest
  Runnable task2 = new Runnable(){
   public void run(){
    System.out.println("value: " + lockTest.getValue());
   }
  };
  //Create a new task execution service
  ExecutorService cachedService = Executors.newCachedThreadPool();
  Future future = null;
  //Task 1 is executed three times at a time, and because the addValue method USES a lock mechanism, it is essentially executed sequentially
  for (int i=0; i<3; i++){
   future = cachedService.submit(task1);
  }
  //Wait for the last task 1 to be completed
  future.get();
  //Execute task 2 again, output the result
  future = cachedService.submit(task2);
  //After waiting for task 2 to complete, close the task execution service
  future.get();
  cachedService.shutdownNow();
 }

 
 public static class ReadWriteLockTest{
  //The lock
  ReadWriteLock lock = new ReentrantReadWriteLock();
  //value
  double value = 0d;
  int addtimes = 0;

  
  public void addValue(double v) {
   //Get writeLock and lock it
   Lock writeLock = lock.writeLock();
   writeLock.lock();
   System.out.println("ReadWriteLockTest to addValue: " + v + "   "
     + System.currentTimeMillis());
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
   }
   try {
    //Do the writing
    this.value += v;
    this.addtimes++;
   } finally {
    //Release writeLock lock
    writeLock.unlock();
   }
  }
  
  public String getInfo() {
   //Get readLock and lock
   Lock readLock = lock.readLock();
   readLock.lock();
   System.out.println("ReadWriteLockTest to getInfo   "
     + System.currentTimeMillis());
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
   }
   try {
    //Do the reading
    return this.value + " : " + this.addtimes;
   } finally {
    //Release readLock
    readLock.unlock();
   }
  }
 }

 public static void testReadWriteLockTest() throws Exception{
  final ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
  //Create task 1 and call the addValue method of lockTest
  Runnable task_1 = new Runnable(){
   public void run(){
    readWriteLockTest.addValue(55.55);
   }
  };
  //Create task 2 and call the getValue method of lockTest
  Runnable task_2 = new Runnable(){
   public void run(){
    System.out.println("info: " + readWriteLockTest.getInfo());
   }
  };
  //Create a new task execution service
  ExecutorService cachedService_1 = Executors.newCachedThreadPool();
  Future future_1 = null;
  //Execute five tasks simultaneously, the first two being task_1 and the last two being task_2
  for (int i=0; i<2; i++){
   future_1 = cachedService_1.submit(task_1);
  }
  for (int i=0; i<2; i++){
   future_1 = cachedService_1.submit(task_2);
  }
  //The last task is task_1
  future_1 = cachedService_1.submit(task_1);
  //The order of execution of these 5 tasks should be:
  //The first task_1 executes, the second task_1 executes; That's because you can't write both, so you have to wait.
  //And then two task_2 execution at the same time; This is because when you write, you can't read, so you wait for the end of the writing,
  //And because they can be read at the same time, they execute at the same time
  //The last task_1 is executed. This is because you cannot write while reading, so you must wait until the end of reading before you can write.

  //Wait for the last task_2 to finish executing
  future_1.get();
  cachedService_1.shutdownNow();
 }
 public static void main(String[] args) throws Exception{
  Lockers.testLockTest();
  System.out.println("---------------------");
  Lockers.testReadWriteLockTest();
 }
}


Related articles: