Using Executors / newSingleThreadExecutor
Hi,
I am investigating using threads using Executors/Callable instead of
the Runnable implementation i normally use.
To simplify my problem i created some code which is shown below.
My expectation was that immediately after submitting a thread using
the submit method, the method returned to the main thread (and
printing "Thread submitted"). Now the output is ;
Thread submitting
Entered thread
java.lang.Exception: Got tired waiting
at theater.CallableTest$MyThread.<init>(CallableTest.java:27)
at theater.CallableTest.startThread(CallableTest.java:46)
at theater.CallableTest.main(CallableTest.java:69)
This implies that MyThread is not started as a new thread but is
called as a method in the main thread.
I probably make a beginners error, but am currently currently unaware
of which ...
Who an help me out ?
Cheers,
Peter
<CODE>
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import theater.Theater.SchrijfTheater;
public class CallableTest {
public class MyThread implements Callable<Boolean> {
Boolean status = false ;
MyThread() throws Exception {
System.out.println("Entered thread") ;
Thread.sleep(5000) ;
throw new Exception("Got tired waiting") ;
}
public Boolean call() throws Exception {
return this.status ;
}
}
public void startThread() {
Future<Boolean> results = null ;
ExecutorService execSvc = Executors.newSingleThreadExecutor();
try {
System.out.println("Thread submitting") ;
results = execSvc.submit(new MyThread());
System.out.println("Thread submitted") ;
results.get(3000,TimeUnit.SECONDS) ;
System.out.println("results!") ;
} catch (CancellationException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CallableTest t = new CallableTest() ;
t.startThread() ;
}
}
</CODE>