Pardon me if the question sounds silly - I am just starting to use Executor.
I have an existing java app that uses threads in this manner-- basically standalone threads are used--
private Thread spawnThread( )
{
Thread t = new Thread()
{
String taskSnap = task.toString();
public void run()
{
try
{
println( task.run( null ) );
}catch( InterruptedException e )
{
println( "ITC - " + taskSnap + " interrupted " );
}
}
};
return t;
}
As you can see from above, the function returns a new thread.
Now in the main() function of the program, a new thread is created in this manner--
taskThread = spawnThread();
taskThread.start();
What i want to do is, create an executor service (with fixed number of threads)--> and then hand off creation of new thread/execution of task by the new thread to that executor.
As I am very new to Executor, what I wish to know is, how do I change the above code so that instead of a new separate thread being formed, a new thread is instead created within the thread pool. I cannot see any command to create a thread (within the thread pool)--> hand off the above task to that thread (and not to a stand-alone thread as above).
Please let me know how to resolve this problem.
Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)
Use java. util. concurrent. Semaphore with number of thread equals 1, so only 1 thread at an time instance can access that resource.
We use the Executors. newSingleThreadExecutor() method to create an ExecutorService that uses a single worker thread for executing tasks. If a task is submitted for execution and the thread is currently busy executing another task, then the new task will wait in a queue until the thread is free to execute it.
In your main, you can write something like this:
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
executor.submit(new Runnable() {
String taskSnap = task.toString();
public void run() {
try {
println(task.run(null));
} catch( InterruptedException e) {
println("ITC - " + taskSnap + " interrupted ");
}
}
});
The submit method will execute the Runnable on one of the threads within the executor service.
Note: Don't forget to shutdown the executor service when you don't need it any more or it will prevent your program from exiting.
Do your research before asking. The idea is to create a class which implements Runnable and execute it using executor service.
Example from: Java Concurrency (Multithreading) - Tutorial
Implementation of the worker (which implements Runnable):
package de.vogella.concurrency.threadpools;
/** * MyRunnable will count the sum of the number from 1 to the parameter * countUntil and then write the result to the console. * <p> * MyRunnable is the task which will be performed * * @author Lars Vogel * */
public class MyRunnable implements Runnable {
private final long countUntil;
MyRunnable(long countUntil) {
this.countUntil = countUntil;
}
@Override
public void run() {
long sum = 0;
for (long i = 1; i < countUntil; i++) {
sum += i;
}
System.out.println(sum);
}
}
How to use executor service to run trigger the worker thread.
package de.vogella.concurrency.threadpools;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
private static final int NTHREDS = 10;
public static void main(String[] args) {
//You can also use Executors.newSingleThreadExecutor() if you just need 1 thread
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
for (int i = 0; i < 500; i++) {
Runnable worker = new MyRunnable(10000000L + i);
executor.execute(worker);
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue.
executor.shutdown();
// Wait until all threads are finish
//while (!executor.isTerminated()) {
//}
//System.out.println("Finished all threads");
//All the threads might not be finished at this point of time. Thread endtime purely depends on the time taken by the processing logic inside your thread.
}
}
You mean something like this?
class Parallel {
private ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public void shutdown() {
pool.shutdown();
}
public void foo() {
pool.submit(new Runnable() {
@Override
public void run() {
// put your code here
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With