Java solves the reader writer problem

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/** * Java solves the reader writer problem **@author zsw
 * @dateShall 2020/08/04 * /
public class Demo6 {
	// Used to implement mutually exclusive access to files, indicating whether any process is currently accessing the shared file
	static Semaphore rw = new Semaphore(1);
	// Records how many reader processes are currently accessing the file
	static volatile AtomicInteger count = new AtomicInteger(0);
	static Semaphore mutex = new Semaphore(1);
	// Write first
	static Semaphore w = new Semaphore(1);

	public static void main(String[] args) {
		for (int i = 0; i < 3; i++) {
			Thread writer = new Thread(new Write());
			writer.setName("writer" + i);
			writer.start();

			Thread read = new Thread(new Read());
			read.setName("read"+ i); read.start(); }}static class Write implements Runnable {
		static int num = 0;

		@Override
		public void run(a) {
			while (true) {
				try {
					w.acquire();
					rw.acquire();
					System.out.println(Thread.currentThread().getName() + "Finished");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					rw.release();
					w.release();
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	static class Read implements Runnable {

		@Override
		public void run(a) {
			try {
				w.acquire();
				mutex.acquire();
				if (count.get() == 0) {
					// The first read process is locked
					rw.acquire();
				}
				count.incrementAndGet();
				mutex.release();
				w.release();
				System.out.println(Thread.currentThread().getName() + "Finished reading.");
				mutex.acquire();
				count.decrementAndGet();
				// Release the critical resource if there is no process to access it
				if (count.get() == 0) {
					rw.release();
				}
				mutex.release();
				Thread.sleep(10);
			} catch(Exception e) { e.printStackTrace(); }}}}Copy the code