Skip to content

Instantly share code, notes, and snippets.

@sbcd90
Created September 11, 2016 02:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbcd90/be341faafc33a1dbb3ea48af037b4e78 to your computer and use it in GitHub Desktop.
Save sbcd90/be341faafc33a1dbb3ea48af037b4e78 to your computer and use it in GitHub Desktop.
package org.example;
import java.util.concurrent.*;
class TestThread implements Runnable {
public final String name;
public final int newcount;
public final long newtimesleep;
public TestThread(String name, int newcount, long newtimeSleep) {
this.name = name;
this.newcount = newcount;
this.newtimesleep = newtimeSleep;
}
public void run() {
int sum = 0;
for (int i=0; i < newcount; i++) {
sum += i;
}
System.out.println(sum);
try {
Thread.sleep(newtimesleep);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ExecutorServiceTest {
private static Future taskTwo = null;
private static Future taskFour = null;
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Runnable taskOne = new TestThread("TasOne", 2, 100);
executorService.execute(taskOne);
for (int i=0; i < 2; i++) {
if (taskTwo == null || taskTwo.isDone() || taskTwo.isCancelled()) {
taskTwo = executorService.submit(new TestThread("TaskTwo", 4, 200));
}
if (taskFour == null || taskFour.isDone() || taskFour.isCancelled()) {
taskFour = executorService.submit(new TestThread("TaskFour", 8, 400));
}
if (taskTwo.get() == null) {
System.out.println("taskTwo finished successfully");
} else {
taskTwo.cancel(true);
}
if (taskFour.get() == null) {
System.out.println("taskFour finished successfully");
} else {
taskFour.cancel(true);
}
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment