/*
* Copyright@ 2011 www.egtry.com
*/
package egtry.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorServiceTest {
public static void main(String[] args) {
ExecutorService service=Executors.newFixedThreadPool(3);
for(int i=0; i<10; i++) {
Worker worker=new Worker();
service.execute(worker);
}
}
public static class Worker implements Runnable {
private static int counter=0;
public synchronized static int incr() {
counter++;
return counter;
}
public synchronized static int decr() {
counter--;
return counter;
}
@Override
public void run() {
long id=Thread.currentThread().getId();
System.out.println("Start Worker: "+id+" total="+incr());
try {
Thread.sleep((int) (Math.random()*3000));
} catch (InterruptedException e) {
}
System.out.println("End Workder: "+id+" total="+decr()+"\n");
}
}
}
Output
Start Worker: 8 total=1
Start Worker: 9 total=2
Start Worker: 10 total=3
End Workder: 8 total=2
Start Worker: 8 total=3
End Workder: 10 total=2
Start Worker: 10 total=3
End Workder: 8 total=2
Start Worker: 8 total=3
End Workder: 9 total=2
Start Worker: 9 total=3
End Workder: 10 total=2
Start Worker: 10 total=3
End Workder: 8 total=2
Start Worker: 8 total=3
End Workder: 9 total=2
Start Worker: 9 total=3
End Workder: 10 total=2
End Workder: 9 total=1
End Workder: 8 total=0