added ex N

This commit is contained in:
Louis Heredero 2024-12-16 15:50:33 +01:00
parent 3c6d89bdd8
commit f2bb16ea85
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 92 additions and 0 deletions

View File

@ -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 +
'}';
}
}

View File

@ -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<News> 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;
}
}

View File

@ -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();
}
}
}