added ex N
This commit is contained in:
parent
3c6d89bdd8
commit
f2bb16ea85
21
src/exercises/ex_n/News.java
Normal file
21
src/exercises/ex_n/News.java
Normal 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 +
|
||||
'}';
|
||||
}
|
||||
}
|
37
src/exercises/ex_n/NewsFeed.java
Normal file
37
src/exercises/ex_n/NewsFeed.java
Normal 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;
|
||||
}
|
||||
}
|
34
src/exercises/ex_n/TestingReentrantReadWriteLock_News.java
Normal file
34
src/exercises/ex_n/TestingReentrantReadWriteLock_News.java
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user