I have a task, it consumes lots of seconds to complete. So I want to know whether using the multithreading concept in Java, can I use multiple threads to perform that single task, so that my task would get done quickly.
Here is my Example. Thread Class:
public class ThreadImpl implements Runnable { @Override public void run() { String value="a"; for (int i = 0; i < 2147483646; i++) { value = value + "b"; } System.out.println("thread task completed " + value); } }
Main Class
public class Main { public static void main(String[] args) { Thread t = new Thread(new ThreadImpl()); t.start(); } }
I want to understand, is it really possible to create multiple threads and execute that task public void run()
alone simultaneously? If yes, how to achieve this?
Advertisement
Answer
Can I use multiple thread to perform [a] single task.
That depends on what you mean by “task.” Your example shows a single function that performs a single computation when it is called by a thread. (Note: It’s not a very interesting computation, but it’s a computation none the less.) If that same function is called by more than one thread, then all that will happen is, each thread will perform the identical computation because that’s the only thing that your function was written to do. No time will be saved.
In order for multiple threads to cooperate on solving some problem, You have to write the code that instructs them to cooperate. You have to write one or more functions that can perform parts of the computation; You have to write code that assigns the different parts to the different threads; and You likely will need to write code that combines the partial results into a single, final result. There is no magic in Java that will automatically re-write your single-threaded code to do those things for you. You have to write it yourself.