Skip to content

Commit

Permalink
Complete sync primitives task
Browse files Browse the repository at this point in the history
  • Loading branch information
JackKaif committed Feb 21, 2024
1 parent 802c4b9 commit b973d87
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
2 changes: 2 additions & 0 deletions java-advanced-ru/sync-primitives/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
.gradle/
build/
caches/
.idea/
13 changes: 12 additions & 1 deletion java-advanced-ru/sync-primitives/src/main/java/exercise/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,18 @@ class App {

public static void main(String[] args) {
// BEGIN

var list = new SafetyList();
var thread1 = new ListThread(list);
var thread2 = new ListThread(list);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(list.getSize());
// END
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
package exercise;

// BEGIN
public class ListThread extends Thread {
SafetyList list;
public ListThread(SafetyList list) {
this.list = list;
}

@Override
public void run() {
for (int i = 0; i < 1000; i++){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
list.add((int) (Math.random() * 1000));
}
}
}
// END
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@

class SafetyList {
// BEGIN

int[] array;
int size;

SafetyList() {
array = new int[2100];
size = 0;
}

synchronized void add(int number) {
array[size] = number;
size++;
}

public int get(int index) {
return index > size ? 0 : array[index];
}

public int getSize() {
return this.size;
}
// END
}

0 comments on commit b973d87

Please sign in to comment.