SL_U2_SJ
Obai Albek 2025-05-23 15:36:29 +02:00
parent 3e6281177a
commit 9982245715
2 changed files with 28 additions and 26 deletions

View File

@ -18,25 +18,25 @@ public class Main {
} }
public static void main(String... args) throws InterruptedException { public static void main(String... args) throws InterruptedException {
list = new ThreadsafeSimplifiedList<>(); list = new ThreadsafeSimplifiedList<>();
for (int i = 0; i < 5000; i++) { for (int i = 0; i < 5000; i++) {
list.add(i); list.add(i);
} }
var thread0 = new Thread(sliceSum(0, 1250, 780625)); var thread0 = new Thread(sliceSum(0, 1250, 780625));
var thread1 = new Thread(sliceSum(1250, 2500, 2343125)); var thread1 = new Thread(sliceSum(1250, 2500, 2343125));
var thread2 = new Thread(sliceSum(2500, 3750, 3905625)); var thread2 = new Thread(sliceSum(2500, 3750, 3905625));
var thread3 = new Thread(sliceSum(3750, 5000, 5468125)); var thread3 = new Thread(sliceSum(3750, 5000, 5468125));
var start = System.currentTimeMillis(); var start = System.currentTimeMillis();
thread0.start(); thread0.start();
thread1.start(); thread1.start();
thread2.start(); thread2.start();
thread3.start(); thread3.start();
thread0.join(); thread0.join();
thread1.join(); thread1.join();
thread2.join(); thread2.join();
thread3.join(); thread3.join();
System.out.printf("%s: %d ms\n", list.getClass().toString(), System.out.printf("%s: %d ms\n", list.getClass().toString(),
System.currentTimeMillis() - start); System.currentTimeMillis() - start);
} }
} }

View File

@ -52,9 +52,8 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
} }
} }
try { try {
return (ptr.element); return delay(ptr.element);
} } finally {
finally {
ptr.lock.unlock(); ptr.lock.unlock();
} }
} }
@ -113,10 +112,13 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
throw new IndexOutOfBoundsException(index + " out of bounds"); throw new IndexOutOfBoundsException(index + " out of bounds");
} }
} }
var prevElement = ptr.element; try {
ptr.element = element; var prevElement = ptr.element;
ptr.lock.unlock(); ptr.element = element;
return prevElement; return prevElement;
} finally {
ptr.lock.unlock();
}
} }
/** /**