Skip to content

Commit

Permalink
Eliminating Thread interference
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnasSmicius committed Jan 6, 2018
1 parent 1a74dc3 commit ed955f8
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 36 deletions.
68 changes: 43 additions & 25 deletions ProducerConsumer/.idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 16 additions & 11 deletions ProducerConsumer/src/com/timbuchalka/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,19 @@ public void run() {
for (String num: nums) {
try {
System.out.println(color + "Adding..." + num);
buffer.add(num);

synchronized (buffer) {
buffer.add(num);
}
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
System.out.println("Producer was interrupted");
}
}

System.out.println(color + "Adding EOF and exiting...");
buffer.add("EOF");
synchronized (buffer) {
buffer.add("EOF");
}
}
}

Expand All @@ -61,14 +64,16 @@ public MyConsumer(List<String> buffer, String color) {

public void run() {
while (true) {
if (buffer.isEmpty()) {
continue;
}
if(buffer.get(0).equals(EOF)) {
System.out.println(color + "Exiting");
break;
} else {
System.out.println(color + "Removed " + buffer.remove(0));
synchronized (buffer) {
if (buffer.isEmpty()) {
continue;
}
if(buffer.get(0).equals(EOF)) {
System.out.println(color + "Exiting");
break;
} else {
System.out.println(color + "Removed " + buffer.remove(0));
}
}
}
}
Expand Down

0 comments on commit ed955f8

Please sign in to comment.