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

时间:2015-07-23 06:37:08

标签: java multithreading

假设我有一个名为Magic()的方法,我想用三个不同的线程执行此方法。 我知道如何用单个线程执行Magic()方法,但我很困惑,我如何处理三个不同的线程?

6 个答案:

答案 0 :(得分:5)

  

假设我有一个名为Magic()的方法,我想用三个不同的线程

执行此方法

创建一个MagicTask类,代表每个task将执行的Thread,并在magic()内调用run()方法:

class MagicTask implements Runnable {
    public void run() {
        magic();
    }

    public void magic() { //do magic }

}

然后创建三个线程并将任务传递给它:

Thread t1 = new Thread(new MagicTask());
Thread t2 = new Thread(new MagicTask());
Thread t3 = new Thread(new MagicTask());

然后启动线程:

t1.start();
t2.start();
t3.start();

注意您也可以将相同的MagicTask实例传递给所有三个Thread实例。请记住,如果MagicTask具有在被不同线程访问时可能变得不一致的状态,则还需要使用synchronized或其他此类构造超出范围使用内部锁定使您的类成为线程安全的对于这个答案。

答案 1 :(得分:0)

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

这里线程t1,t2,t3正在调用相同的方法call()。

答案 2 :(得分:0)

如果您使用的是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();
    }
}

如果魔法不是静态方法,请使用:

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

答案 3 :(得分:0)

您可以尝试使用。

  

我将任务划分为不同的线程   尝试自己的逻辑,这只是一个简单的偶数,

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

    }

}

答案 4 :(得分:-1)

直接调用magic();,为了更好的结果,请按照下面的方法同步

public synchronized void magic(){ 
              //your code 
}

答案 5 :(得分:-1)

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

            }
}
}