From f2bb16ea85f0ce5a00b3b9d86c42707bc528018c Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Mon, 16 Dec 2024 15:50:33 +0100 Subject: [PATCH] added ex N --- src/exercises/ex_n/News.java | 21 +++++++++++ src/exercises/ex_n/NewsFeed.java | 37 +++++++++++++++++++ .../TestingReentrantReadWriteLock_News.java | 34 +++++++++++++++++ 3 files changed, 92 insertions(+) create mode 100644 src/exercises/ex_n/News.java create mode 100644 src/exercises/ex_n/NewsFeed.java create mode 100644 src/exercises/ex_n/TestingReentrantReadWriteLock_News.java diff --git a/src/exercises/ex_n/News.java b/src/exercises/ex_n/News.java new file mode 100644 index 0000000..36ba6d6 --- /dev/null +++ b/src/exercises/ex_n/News.java @@ -0,0 +1,21 @@ +package exercises.ex_n; + +import java.time.LocalDateTime; + +public class News { + private String news; + private LocalDateTime date; + + public News(String news) { + this.news = news; + this.date = LocalDateTime.now(); + } + + @Override + public String toString() { + return "News{" + + "news='" + news + '\'' + + ", date=" + date + + '}'; + } +} diff --git a/src/exercises/ex_n/NewsFeed.java b/src/exercises/ex_n/NewsFeed.java new file mode 100644 index 0000000..491af1c --- /dev/null +++ b/src/exercises/ex_n/NewsFeed.java @@ -0,0 +1,37 @@ +package exercises.ex_n; + +import java.util.Stack; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class NewsFeed { + private final Stack newsStack = new Stack<>(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final Lock writeLock = lock.writeLock(); + private final Lock readLock = lock.readLock(); + + public NewsFeed() { + + } + + public void put(News news) { + try { + writeLock.lock(); + newsStack.push(news); + } finally { + writeLock.unlock(); + } + } + + public News read() { + News news; + try { + readLock.lock(); + news = newsStack.peek(); + } finally { + readLock.unlock(); + } + return news; + } +} diff --git a/src/exercises/ex_n/TestingReentrantReadWriteLock_News.java b/src/exercises/ex_n/TestingReentrantReadWriteLock_News.java new file mode 100644 index 0000000..3fd1192 --- /dev/null +++ b/src/exercises/ex_n/TestingReentrantReadWriteLock_News.java @@ -0,0 +1,34 @@ +package exercises.ex_n; + +public class TestingReentrantReadWriteLock_News { + public static void main(String[] args) { + NewsFeed newsFeed = new NewsFeed(); + newsFeed.put(new News("START OF NEWS")); + + // Create one writing thread + new Thread(new Runnable() { + @Override + public void run() { + for (int i=0;i<200;i++) { + newsFeed.put(new News("News " + i)); + } + } + }).start(); + + // Create several reading threads + for (int i=0; i<20;i++) { + new Thread((new Runnable() { + @Override + public void run() { + for (int i=0;i<20;i++) { + News news = newsFeed.read(); + if (news != null) { + System.out.println("News read : " + + newsFeed.read()); + } + } + } + })).start(); + } + } +}