Skip to content

Commit

Permalink
Thread pools and ExecutionService
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnasSmicius committed Jan 10, 2018
1 parent 82faeaf commit fc6efc4
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 11 deletions.
34 changes: 26 additions & 8 deletions ProducerConsumer/.idea/workspace.xml

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

28 changes: 25 additions & 3 deletions ProducerConsumer/src/com/timbuchalka/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

import static com.timbuchalka.Main.EOF;
Expand All @@ -13,13 +14,34 @@ public class Main {
public static void main(String[] args) {
List<String> buffer = new ArrayList<>();
ReentrantLock bufferLock = new ReentrantLock();

ExecutorService executorService = Executors.newFixedThreadPool(3);

MyProducer producer = new MyProducer(buffer, ThreadColor.ANSI_RED, bufferLock);
MyConsumer consumer1 = new MyConsumer(buffer, ThreadColor.ANSI_PURPLE, bufferLock);
MyConsumer consumer2 = new MyConsumer(buffer, ThreadColor.ANSI_CYAN, bufferLock);

new Thread(producer).start();
new Thread(consumer1).start();
new Thread(consumer2).start();
executorService.execute(producer);
executorService.execute(consumer1);
executorService.execute(consumer2);

Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println(ThreadColor.ANSI_GREEN + "I'm being printed from the Callable class");
return "This is the callable result";
}
});

try {
System.out.println(future.get());
} catch (ExecutionException e) {
System.out.println("Something went wrong");
} catch (InterruptedException e) {
System.out.println("Thread running the task was interrupted");
}

executorService.shutdown();
}
}

Expand Down

0 comments on commit fc6efc4

Please sign in to comment.