I have code with using thread but i don't use thread from java.util.concurrent so i want change my code, but i have some issue.
Thread thread = new Thread() {
public void run() {
doSomething();
}
};
I want use executor like this Thread, so how I can do this?Is similar way to do this in java.util.concurrent?I tried that:
ExecutorService executorService = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
public void run() {
//my code doing something
}
};
Also I Have:
List<Runnable> threadsList = new ArrayList<Runnable>();
and I have method:
boolean isAllowedCreateNewThread(Runnable taskToRun){
for(int i = 0; i < threadsList.size(); i++){
Runnable th = threadsList.get(i);
if(th.isAlive())doSomething(); //isAlive doesn't work since I have runnable instead of Thread
boolean isAllowed = true ;//I have here some bool function but it doesn't matter
if(isAllowed){
threadsList.add(taskToRun);
//service.submit(taskToRun);
executorService.execute(taskToRun);
}
return isAllowed;
}
if I have
List<Thread> threadsList = new ArrayList<Thread>();
and don't use ExecutorService and change everywhere Runnable to Thread it work's.
So I think that it also I have to change, but how? What is Keyword insted Thread?Runnable? Or something else?
Also I have:
for(int i = 0; i < threadsList.size(); i++){
Thread th = threadsList.get(i);
if(th.isAlive())doSomething(); myThreadName.start();
I have to change isAlive()
to something similar in java.util.concurrent
and myThreadName.start();
So generally I want change this code using Thread class to code using threads from java.util.concurrent
You can replace your code with below code segment.
Create a Runnable class.
Create a executor service with required number of threads. This creates a pool of required number of threads.
Create your Runnable for each thread present in the pool and assign it to your executor.
Sample Output
So the entire code will look like: