Skip to content

Instantly share code, notes, and snippets.

@komamitsu
Created February 7, 2012 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komamitsu/1760759 to your computer and use it in GitHub Desktop.
Save komamitsu/1760759 to your computer and use it in GitHub Desktop.
Executors sample
package com.komamitsu;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App {
private static class MyRunnable implements Runnable {
private int num = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
num++;
System.out.println(String.valueOf(num));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
ExecutorService executor = Executors.newSingleThreadExecutor();
System.out.println("========== 1 ===========");
executor.execute(myRunnable1);
System.out.println("========== 2 ===========");
executor.execute(myRunnable2);
System.out.println("========== 3 ===========");
executor.shutdown();
}
}
========== 1 ===========
========== 2 ===========
1
========== 3 ===========
2
3
4
5
1
2
3
4
5
package com.komamitsu;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App {
private static class MyRunnable implements Runnable {
private int num = 0;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
num++;
System.out.println(String.valueOf(num));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyRunnable myRunnable1 = new MyRunnable();
MyRunnable myRunnable2 = new MyRunnable();
ExecutorService executor = Executors.newFixedThreadPool(2);
System.out.println("========== 1 ===========");
executor.execute(myRunnable1);
System.out.println("========== 2 ===========");
executor.execute(myRunnable2);
System.out.println("========== 3 ===========");
executor.shutdown();
}
}
========== 1 ===========
========== 2 ===========
========== 3 ===========
1
1
2
2
3
3
4
4
5
5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment