简体   繁体   English

如何使用三个不同的线程调用同一方法

[英]How can I call a same method with three different thread

Suppose I have a method called Magic() I want to execute this method with three different thread. 假设我有一个名为Magic()的方法,我想用三个不同的线程执行此方法。 I know how to execute Magic() method with a single thread, but I am confuse, How do I do with three different threads? 我知道如何使用单个线程执行Magic()方法,但我感到困惑,如何使用三个不同的线程?

Suppose I have a method called Magic() I want to execute this method with three different thread 假设我有一个名为Magic()的方法,我想用三个不同的线程执行此方法

Create a MagicTask class that represents the task that each Thread will execute and call the magic() method inside run() : 创建一个MagicTask类来表示每个Thread将执行的task ,并在run()内调用magic()方法:

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. 注意您也可以将相同的MagicTask实例传递给所有三个Thread实例。 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. 请记住,如果MagicTask状态在被不同的线程访问时可能变得不一致,那么您还需要使用synchronized或其他此类构造使用内部锁定来使您的类线程安全,而此构造不在此答案的范围之内。

 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(). 在这里,线程t1,t2,t3调用相同的方法call()。

If you are using Java 8, function references are straightforward: 如果您使用的是Java 8,则函数引用非常简单:

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();
    }
}

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();

    }

}

Call it directly like magic(); magic();一样直接调用它magic(); And for better result synchronize that method like below 为了获得更好的结果,请像下面这样同步该方法

public synchronized void magic(){ 
              //your code 
}
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()) {}

            }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从线程中调用与run()不同的方法 - How can I call a different method than run() from a Thread 如何在同一Activity中调用将在同一文件上但在不同时间使用的两个方法? - How can I call two method in the same Activity that will work on the same file but in different times? 如何使用Mockito测试对同一方法的两个不同调用,每个调用返回不同的响应? - How can I use Mockito to test two different calls to the same method that returns a different response for each call? 如何让6个按钮在Android中使用不同的参数调用相同的方法? - How can I let 6 buttons call the same method with different parameters in Android? 可以在不同的线程上调用相同的方法吗? - Can you call the same method on different threads? 如何从另一个线程调用线程的getHandler()方法? - How can I call a thread's getHandler() method from another thread? Spring 不同线程调用方法 - Spring call method in different thread 不同的ID如何在Android中调用相同的方法 - Different ID how will call on same method in android 如何以相同的方法返回不同的对象? - How can i return different objects in same method? 如何在 Java 中使用相同的循环 scope 三个不同的条件? - How can I scope three different conditions using the same loop in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM