Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package multithreading.semaphore.syncrhonization;
- import java.util.ArrayList;
- import java.util.List;
- public class SharedResource {
- private final MySynchronizedSemaphore semaphore;
- public final List<String> data = new ArrayList<>();
- public SharedResource(MySynchronizedSemaphore semaphore) {
- this.semaphore = semaphore;
- }
- public void doSomeAtomicStuff() throws InterruptedException {
- semaphore.acquire();
- data.add(Thread.currentThread().getName());
- semaphore.release();
- }
- }
- package multithreading.semaphore.syncrhonization;
- import java.util.ArrayList;
- import java.util.List;
- public class SharedResource {
- private final MySynchronizedSemaphore semaphore;
- public final List<String> data = new ArrayList<>();
- public SharedResource(MySynchronizedSemaphore semaphore) {
- this.semaphore = semaphore;
- }
- public void doSomeAtomicStuff() throws InterruptedException {
- semaphore.acquire();
- data.add(Thread.currentThread().getName());
- semaphore.release();
- }
- }
- Client
- package multithreading.semaphore.syncrhonization;
- public class Client {
- public static void main(String[] args) throws InterruptedException {
- MySynchronizedSemaphore semaphore = new MySynchronizedSemaphore();
- SharedResource sharedResource = new SharedResource(semaphore);
- for (int i = 0; i < 500_000; i++) {
- Thread thread = new Thread(() -> {
- try {
- sharedResource.doSomeAtomicStuff();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- });
- thread.start();
- thread.join();
- }
- System.out.println("Size of the list is " + sharedResource.data.size());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement