问题
Is there an upper limit on the number of Swing Worker threads that can be run or is it like as far as the memory supports? Also is this configurable somewhere?
回答1:
A SwingWorker
is not a thread itself but a task that will be executed in a thread. Usually, you would use an ExecutorService
to execute instances of SwingWorker
; this interface also allows to set the number of threads:
int n = 20; // Maximum number of threads
ExecutorService threadPool = Executors.newFixedThreadPool(n);
SwingWorker w; //don't forget to initialize
threadPool.submit(w);
Now, if you submit more than n SwingWorker
instances, they'll have to queue up and wait until a thread from the pool gets available.
回答2:
final int corePoolSize = 100;
final int maximumPoolSize = 100;
final long keepAliveTime = 100000;
final TimeUnit unit = TimeUnit.SECONDS;
final BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(maximumPoolSize);
sun.awt.AppContext.getAppContext().put(SwingWorker.class,
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue));
The above code sample will allow you to have more than the default number of SwingWorkers executing. Of course it is accessing some backdoor sun.awt.AppContext class, but it is a quick workaround for those interested, and not able/willing to provide their own ExecutorService.
来源:https://stackoverflow.com/questions/8356784/whats-the-maximum-number-of-swing-worker-threads-that-can-be-run