Java多线程_读写锁_读者写者问题
读者写者问题
读写锁
new ReentrantReadWriteLock()
- 读读共享
- 读写互斥
- 写写互斥
代码
public class ReadWriteLockDemo { static class Service { ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); Lock readLock = readWriteLock.readLock(); Lock writeLock = readWriteLock.writeLock(); public void read() { try { readLock.lock(); //申请获得读锁 System.out.printf("%s开始获得读锁,开始读取数据的时间%s ; ", Thread.currentThread().getName(), System.currentTimeMillis()); Thread.sleep(1000);//模拟读数据 } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf("%s读取数据完毕的时间%s ", Thread.currentThread().getName(), System.currentTimeMillis()); readLock.unlock();//释放锁 } } public void write() { try { writeLock.lock();//申请获得写锁 System.out.printf("%s获得写锁,开始修改数据%s ;", Thread.currentThread().getName(), System.currentTimeMillis()); Thread.sleep(5000);//模拟写数据 } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf("%s修改数据完毕时间%s ", Thread.currentThread().getName(), System.currentTimeMillis()); writeLock.unlock();//释放写锁 } } } static void readRead(Service service) { System.out.println("读读共享 测试结果:"); //读读共享 for (int i = 0; i < 5; i++) { Thread thread = new Thread(() -> service.read()); thread.setName(String.format("readThread%d", i)); thread.start(); //定义一个线程读数据 } } static void writeWrite(Service service) { System.out.println("写写互斥 测试结果:"); //写写互斥 for (int j = 0; j < 5; j++) { Thread thread = new Thread(() -> service.write()); thread.setName(String.format("readThread%d", j)); thread.start();//定义一个线程写数据 } } static void readWrite(Service service) { System.out.println("读写互斥 测试结果:"); //读写互斥 for (int k = 5; k < 10; k++) { Thread thread1 = new Thread(() -> service.read()); thread1.setName(String.format("readThread%d", k)); thread1.start(); //定义一个线程读数据 Thread thread2 = new Thread(() -> service.write()); thread2.setName(String.format("readThread%d", k)); thread2.start();//定义一个线程写数据 } } public static void main(String[] args) { Service service = new Service(); //以下三个方法请单独运行 //读读共享 result:多个读线程读取数据时间戳一致 readRead(service); //写写互斥 result:写线程同时只能运行一个 readWrite(service); //读写互斥 result:读写线程同时只能运行一个读线程或者写线程 writeWrite(service); } }
部分笔试题实例
该部分面试题/笔试题实例来自 @ 例如如下面试题,以上模板可以解决面试题7;问题3-6解法 见本人前两篇文章
-
第七题 读者写者问题 这也是一个非常经典的多线程题目,题目大意如下:有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者读时写者也不能写。 依据本例稍作改动即可
下一篇:
Request请求参数中文乱码处理