Priority ThreadPoolExecutor in Java (Android)

I am trying to make ThreadPoolExecutor with priority. Therefore I define

private static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL, MAXPOOL, TimeUnit.SECONDS, queue, new mThreadFactory()); 

So, the key is a link to the queue. But when I declare:

 static PriorityBlockingQueue<mDownloadThread> queue=new PriorityBlockingQueue<mDownloadThread>(MAXPOOL,new DownloadThreadComparator()); 

The compiler throws an error in the first line: The ThreadPoolExecutor constructor (int, int, int, TimeUnit, PriorityBlockingQueue, FileAccess.mThreadFactory) has undefined with one quick value: the change type is 'queue' to BlockingQueue. Can you help me understand what the problem is?

thanks

Additional Information:

For comparison runnables, I implement the following class

 class mDownloadThread implements Runnable{ private Runnable mRunnable; private int priority; mDownloadThread(Runnable runnable){ mRunnable=runnable; } @Override public void run() { mRunnable.run(); } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } } 

Comparator:

 class DownloadThreadComparator implements Comparator<mDownloadThread>{ @Override public int compare(mDownloadThread arg0, mDownloadThread arg1) { if (arg0==null && arg1==null){ return 0; } else if (arg0==null){ return -1; } else if (arg1==null){ return 1; } return arg0.getPriority()-arg1.getPriority(); } } 
+6
source share
2 answers

ThreadPoolExecutor constructor accepts a BlockingQueue<Runnable> rather than a BlockingQueue<? extends Runnable> BlockingQueue<? extends Runnable> , so you cannot pass it an instance of PriorityBlockingQueue<mDownloadThread> .

You can change the queue type to PriorityBlockingQueue<Runnable> , but in this case you cannot implement Comparator<mDownloadThread> without using the compare method.

Another solution is to bypass general type checking, but you are responsible for sending only instances of the mDownloadThread to execute method:

 static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL, MAXPOOL, TimeUnit.SECONDS, (PriorityBlockingQueue) queue, new mThreadFactory()); 
+6
source

The problem is that ThreadPoolExecutor expects a BlockingQueue<Runnable> , and you pass PriorityBlockingQueue<mDownloadThread> . PriorityBlockingQueue implements BlockingQueue , so this is not a problem. The problem is Runnable . You cannot pass the generic type mDownloadThread where Runnable was expected.

The following is fixed:

 static PriorityBlockingQueue<Runnable> queue=new PriorityBlockingQueue<Runnable>(MAXPOOL,new DownloadThreadComparator()); 

& &

 class DownloadThreadComparator implements Comparator<Runnable>{ 

If ThreadPoolExecutor were written to accept BlockingQueue<? extends Runnable> BlockingQueue<? extends Runnable> what you have.

+4
source

Source: https://habr.com/ru/post/899450/


All Articles