Suppose I have a method called Magic() I want to execute this method with three different thread. I know how to execute Magic() method with a single thread, but I am confuse, How do I do with three different threads?
-
Just call it. Assuming that each thread has either a different or same instance of the object, just call it like normal... – MadProgrammer Jul 23 '15 at 06:38
-
have you tried coding and running it? please try and add your code – VedantK Jul 23 '15 at 06:40
-
Make sure you sync it. – joey rohan Jul 23 '15 at 06:40
-
2Why do you have a method called `Magic`? We use `camelCase` for method names in Java. – Boris the Spider Jul 23 '15 at 06:44
-
@joeyrohan that would completely defeat the object of calling the method simultaneously would it not? Random statements made without actually knowing what the OP is trying to do and why are entirely unhelpful - to the extent of being harmful. – Boris the Spider Jul 23 '15 at 06:45
-
Call it directly like magic(); And for better result synchronize that method like below public synchronized void magic(){ //your code } – Vishwajit R. Shinde Jul 23 '15 at 06:47
-
What is the purpose. Any method can be called from any number of threads. If the method uses some variables which are globally accessible and modifiable then you should use classes which can handle concurrency. I am still missing the point of the question. – panther Jul 23 '15 at 06:47
-
@Boris the Spider I am sorry, I wrote it for an example. What i am trying to do is, I have method which do some task, which is taking long time to do the work and run by main thread, instead if I run the same method with multiple thread , i guess the execution time will reduce – Varun Jul 23 '15 at 06:56
-
1@varun That is not the ideal approach. Can you logically divide the task so that it can run simultaneously. e.g If you are processing 100 records, doing the same task on each record. Then you can divide the task to multiple threads handling part of the records. I highly suggest you read the producer consumer pattern for these kind of jobs. – panther Jul 23 '15 at 07:01
-
@BoristheSpider What if all the fields are just messed up by different threads? Use of calling the method by overlooking memory consistency errors? – joey rohan Jul 23 '15 at 07:09
-
@ panther Exactly.. The same I am trying to do. – Varun Jul 23 '15 at 07:12
-
1@varun, use synchronized block or method, so that your method will accessed for every thread with a lock. And therefore you will be assurred with your concurrent data – Vishwajit R. Shinde Jul 23 '15 at 07:29
-
@VishwajitR.Shinde a `synchronized` block will make the code exactly the opposite of concurrent. This is almost **never** the right approach when using threads to speed up processing. Sadly one cannot down vote comments. – Boris the Spider Jul 23 '15 at 08:13
-
@BoristheSpider You could try flagging the comment :). I did have success with it once. Maybe the mod did not dig into it too much.. – Chetan Kinger Jul 23 '15 at 08:52
-
@BoristheSpide can u give me some hint how do I proceed – Varun Jul 23 '15 at 09:01
-
@varun with the information given. No. Calling a method 3 times will make it run 3 times - it will not make it run faster. You need to provide an [SSCCE](http://sscce.org/) of your code and some attempt to parallelise it yourself. – Boris the Spider Jul 23 '15 at 09:03
6 Answers
Suppose I have a method called Magic() I want to execute this method with three different thread
Create a MagicTask
class that represents the task
that each Thread
will execute and call the magic()
method inside run()
:
class MagicTask implements Runnable {
public void run() {
magic();
}
public void magic() { //do magic }
}
Then create three threads and pass it the task :
Thread t1 = new Thread(new MagicTask());
Thread t2 = new Thread(new MagicTask());
Thread t3 = new Thread(new MagicTask());
Then start the threads :
t1.start();
t2.start();
t3.start();
Note You can pass the same MagicTask
instance to all three Thread
instances as well. Remember that if MagicTask
has state that can get inconsistent when accessed by different threads, you also need to make your class thread-safe by using intrinsic locking using synchronized
or other such constructs which are out of the scope for this answer.

- 15,069
- 6
- 45
- 82
-
@varun You can upvote and mark this as the accepted answer then :). If you have more questions relating to the actual problem you are trying to solve, post a new question on the site instead of editing this question and I will be glad to help. – Chetan Kinger Jul 23 '15 at 07:04
-
can you please look into this question? https://stackoverflow.com/questions/64134839/how-to-call-a-method-with-multiple-threads?noredirect=1#comment113412523_64134839 – Jeb Sep 30 '20 at 09:52
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
call();
}
void call(){
System.out.println("method call by"+Thread.currentThread().getName());
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
Thread t2 =new Thread(m1);
Thread t3 =new Thread(m1);
t1.start();
t2.start();
t3.start();
}
}
Here Thread t1,t2,t3 are calling the same method call().

- 315
- 3
- 13
-
How can I send arguments to the call method? if my call method accepts arguments? – Suraj Jul 21 '22 at 14:33
If you are using Java 8, function references are straightforward:
public class Main {
public static void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
new Thread(Main::magic).start();
new Thread(Main::magic).start();
new Thread(Main::magic).start();
}
}
And if magic isn't a static method use:
public class Main {
public void magic() {
System.out.println("this is magic");
}
public static void main(final String args[]) {
Main m = new Main();
new Thread(m::magic).start();
new Thread(m::magic).start();
new Thread(m::magic).start();
}
}

- 203
- 2
- 8
-
If using Java 8 you would use a [`CompleteableFuture`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html). This is a strange hybrid of arcane `Thread` based code and modern Java. It should never happen. – Boris the Spider Jul 23 '15 at 08:11
-
The author wants to know how to call the same method with three different thread. My solution is easy to understand and maintain. [CompleteableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html) on the other hand is more complex and less intuitive. My suggestion: Keep things simple. – Marcel Jul 23 '15 at 10:21
You can try Like.
I am dividing the task to different thread Try your own logic it just a simple even count,
public class CountNumber implements Runnable {
int stop;
int start;
int totalEvenNo;
public CountNumber(int start, int stop)
{
this.start=start;
this.stop=stop;
}
public void run()
{
int total= countEven(start, stop);
System.out.println("Total Even numbers are :"+total);
}
public int countEven(int str,int stp)
{
for(int i=str;i<=stp;i++)
{
if(i%2==0)
{
totalEvenNo +=1;
System.out.println(totalEvenNo);
}
}
return totalEvenNo;
}
}
public class MainClassNumber {
public static void main(String[] args) {
System.out.println("Spawaning Thread.........");
Thread t1 = new Thread(new CountNumber(0, 500000));
Thread t2 = new Thread(new CountNumber(500001, 2000000));
Thread t3 = new Thread(new CountNumber(2000001, 5000000));
Thread t4 = new Thread(new CountNumber(5000001, 10000000));
Thread t5 = new Thread(new CountNumber(10000001, 20000000));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
-
This `System.out.println(totalEvenNo)` is most likely a synchronized method (although not guaranteed to be, it is in practice). That means this code does **absolutely no parallelisation**. All it does is create multiple threads which take it in turn to print - this taking in turns means that the code is **not** concurrent. – Boris the Spider Jul 23 '15 at 08:09
Call it directly like magic();
And for better result synchronize that method like below
public synchronized void magic(){
//your code
}

- 465
- 2
- 5
- 18
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
public void run() {
Magic();
}
private void Magic() {
// consider synchronizing this method, but if you do method will be accessable by one thread at a time.
}
}
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3)
for (int i = 0; i < 3; i++) {
Runnable worker = new WorkerThread();
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {}
}
}
}

- 1,886
- 2
- 15
- 33
-
This `while (!executor.isTerminated()) { }` is **busy wait**. It spins a single `Thread` on the `while` which uses it at 100% whilst waiting - taking it out of play for the duration of the wait. Modern code should **never** do this, **ever**. There are numerous ways of using a proper wait, for example [`ExecutorService.awaitTermination`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination-long-java.util.concurrent.TimeUnit-) or a [`Semaphore`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html) – Boris the Spider Jul 24 '15 at 07:20
-