Finished Thread Pool example code.

This commit is contained in:
Ilkka Seppala
2015-05-17 18:08:50 +03:00
parent 4c0a300b86
commit 6e76227143
5 changed files with 111 additions and 0 deletions

View File

@ -1,7 +1,41 @@
package com.iluwatar;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App {
public static void main( String[] args ) {
System.out.println("Program started");
List<Task> tasks = new ArrayList<>();
tasks.add(new PotatoPeelingTask(3));
tasks.add(new PotatoPeelingTask(6));
tasks.add(new CoffeeMakingTask(2));
tasks.add(new CoffeeMakingTask(6));
tasks.add(new PotatoPeelingTask(4));
tasks.add(new CoffeeMakingTask(2));
tasks.add(new PotatoPeelingTask(4));
tasks.add(new CoffeeMakingTask(9));
tasks.add(new PotatoPeelingTask(3));
tasks.add(new CoffeeMakingTask(2));
tasks.add(new PotatoPeelingTask(4));
tasks.add(new CoffeeMakingTask(2));
tasks.add(new CoffeeMakingTask(7));
tasks.add(new PotatoPeelingTask(4));
tasks.add(new PotatoPeelingTask(5));
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i=0; i<tasks.size(); i++) {
Runnable worker = new Worker(tasks.get(i));
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Program finished");
}
}

View File

@ -0,0 +1,15 @@
package com.iluwatar;
public class CoffeeMakingTask extends Task {
private static int TIME_PER_CUP = 300;
public CoffeeMakingTask(int numCups) {
super(numCups * TIME_PER_CUP);
}
@Override
public String toString() {
return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
}
}

View File

@ -0,0 +1,15 @@
package com.iluwatar;
public class PotatoPeelingTask extends Task {
private static int TIME_PER_POTATO = 500;
public PotatoPeelingTask(int numPotatoes) {
super(numPotatoes * TIME_PER_POTATO);
}
@Override
public String toString() {
return String.format("%s %s", this.getClass().getSimpleName(), super.toString());
}
}

View File

@ -0,0 +1,27 @@
package com.iluwatar;
public abstract class Task {
private static int nextId = 1;
private int id;
private int timeMs;
public Task(int timeMs) {
this.id = nextId++;
this.timeMs = timeMs;
}
public int getId() {
return id;
}
public int getTimeMs() {
return timeMs;
}
@Override
public String toString() {
return String.format("id=%d timeMs=%d", id, timeMs);
}
}

View File

@ -0,0 +1,20 @@
package com.iluwatar;
public class Worker implements Runnable {
private Task task;
public Worker(Task task) {
this.task = task;
}
@Override
public void run() {
System.out.println(String.format("%s processing %s", Thread.currentThread().getName(), task.toString()));
try {
Thread.sleep(task.getTimeMs());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}