added ex S3

This commit is contained in:
Louis Heredero 2025-01-07 13:27:38 +01:00
parent 9be4e8a359
commit c89a9b3a90
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
5 changed files with 124 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package exercises.ex_s3;
public abstract class AbstractTweet {
private String author;
private String content;
public AbstractTweet(String author, String content) {
this.author = author;
this.content = content;
}
public abstract void addLike();
public abstract void removeLike();
public abstract long getLikes();
@Override
public String toString() {
return "@" + author + " tweeted \"" + content + "\" (" + getLikes() + " likes)";
}
}

View File

@ -0,0 +1,27 @@
package exercises.ex_s3;
import java.util.concurrent.atomic.AtomicLong;
public class AtomicTweet extends AbstractTweet {
private AtomicLong likes = new AtomicLong(0);
public AtomicTweet(String author, String content) {
super(author, content);
}
@Override
public void addLike() {
likes.incrementAndGet();
}
@Override
public void removeLike() {
likes.updateAndGet(i -> i > 0 ? i - 1 : i);
}
@Override
public long getLikes() {
return likes.get();
}
}

View File

@ -0,0 +1,32 @@
package exercises.ex_s3;
import java.util.ArrayList;
import java.util.List;
public class TestingAtomicLong {
public static String[] names = {
"Alice", "Bob", "Charlie", "Derek", "Emily",
"Fionna", "Greg", "Harry", "Isabella", "Julia"
};
public static void main(String[] args) throws InterruptedException {
List<AbstractTweet> tweets = new ArrayList<>();
AbstractTweet tweet1 = new Tweet("Alice", "Java is cool !");
AbstractTweet tweet2 = new AtomicTweet("Bob", "ISC is the best !");
tweets.add(tweet1);
tweets.add(tweet2);
Thread[] users = new Thread[10];
for (int i = 0; i < 10; i++) {
users[i] = new Thread(new User(names[i], tweets));
users[i].start();
}
for (int i = 0; i < 10; i++) {
users[i].join();
}
System.out.println(tweet1);
System.out.println(tweet2);
}
}

View File

@ -0,0 +1,21 @@
package exercises.ex_s3;
public class Tweet extends AbstractTweet {
private long likes = 0;
public Tweet(String author, String content) {
super(author, content);
}
public void addLike() {
likes += 1;
}
public void removeLike() {
likes -= 1;
}
public long getLikes() {
return likes;
}
}

View File

@ -0,0 +1,24 @@
package exercises.ex_s3;
import java.util.List;
public class User implements Runnable {
private final String name;
private final List<AbstractTweet> tweets;
public User(String name, List<AbstractTweet> tweets) {
this.name = name;
this.tweets = tweets;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
if (i % 10 == 9) {
tweets.forEach(AbstractTweet::removeLike);
} else {
tweets.forEach(AbstractTweet::addLike);
}
}
}
}