I am implement a thread pool for my application and I want to use newCachedThreadPool along with ThreadFactory, and I wonder what I wrote below is correct.
1.The idea of using newCachedThreadPool is that thread can be reusable, and that idle thread will be terminated appropriately like the jdk7 doc provided. However, when I wrote the code, I have some doubt since in newThread(Runnable r)
, I return new instance of MyThread
, and I also does MyThread myThread = new MyThread();
in main
. So please if an experienced developers can point out whether what I did below are correct or not, I would greatly appreciated. Thank you
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class ThreadFactoryTest{
public static void main(String[] args) {
ExecutorService cachedPool = Executors.newCachedThreadPool(new MyThreadFactory());
MyThread myThread = new MyThread();
cachedPool.submit(myThread);
}
}
class MyThreadFactory implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
return new MyThread(r);
}
}
class MyThread extends Thread {
public MyThread(Runnable r){
super(r);
}
public MyThread(){
super();
}
@Override
public void run() {
Thread t = Thread.currentThread();
if(t instanceof MyThread){
System.out.println("Thread is MyThread");
}
System.out.println("Inside: " + this.getName());
Utils.awesome();
}
}
class Utils{
public static void awesome(){
Thread t = Thread.currentThread();
if(t instanceof MyThread){
System.out.println("Inside awesome() and Thread is MyThread. Provide special awesomeness for MyThread.");
}
}
}
When I run the above program it produces
Thread is MyThread
Inside: Thread-1
Inside awesome() and Thread is MyThread. Provide special awesomeness for MyThread.
which are the correct outputs, what I am asking is whether I am setting up correctly.