如果Runnable在ExecutorService中执行了多次会发生什么

时间:2015-07-17 06:54:51

标签: java multithreading executorservice

如果一个线程多次执行同一次,会发生什么。让我们说我有线程

private Runnable mySampleThread() {
    return new Runnable() {
        @Override
        public void run() {
        //something is going on here.

        }
    };
}

我创建了一个固定线程池为10的ExecutorService。如果我在mySampleThread中执行ExecutorService 10次,会发生什么。 如下所示,

ExecutorService mySampleExecutor = Executors.newFixedThreadPool(10);
while (i <= 10) {
    mySampleExecutor.execute(mySampleThread);
    i++;
}

4 个答案:

答案 0 :(得分:3)

答案很简单。执行程序将执行Runnable对象(它不是Thread对象),如文档Interface Executor中所述

  

将来某个时间执行给定的命令。该命令可以在Executor实现的判断下在新线程,池化线程或调用线程中执行。

基本上,Executor将获取它的内部池(ThreadPoolExecutor)的一个线程,为其分配runnable执行run()方法。

答案 1 :(得分:1)

首先详细说明您的问题或查询。

尽管如此,假设您正在调用方法“mySampleThread()”而不会丢失括号。此方法实际上每次都返回一个新的Runnable对象,因此您将所有10次运行新的runnable传递给执行程序。这意味着您向执行者提交了10个不同的任务。因此,如果执行程序为每个任务创建不同的线程(这取决于它的实现),那么无论你在run()中编码什么,都将在10个不同的线程中执行10次。

如其他答案中所述,传递给执行程序的runnable对象不是线程。

希望它澄清一下。

顺便说一句,您可以尝试运行该程序。

答案 2 :(得分:1)

正如其他答案明确指出的那样,将会有与调用次数一样多的新线程(由于使用的执行程序可能更少,我专注于Runnable重用,限制执行程序的线程数量很好在其他答案中解释)。所有这些都是使用单个Runnable对象创建的。

值得一提的是,我个人多次使用它 - 这是在多个线程之间共享数据的方法之一,因为所有这些线程共享用于创建的Runnable。同步问题在这一点上发挥作用,但这是另一个故事。

这是显示典型用法和上述同步问题的代码。

import java.util.concurrent.ExecutorService;

class MyThread implements Runnable {
    public int counter = 0;

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            counter++;
        }
    }
}

class MySynchronizedThread implements Runnable {
    public int counter = 0;

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            synchronized (this) {
                counter++;
            }
        }
    }
}

public class RunnableTest {

    public static void main(String[] args) throws InterruptedException {

        MyThread runnableObject = new MyThread();
        ExecutorService ex = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            ex.execute(runnableObject);
        }


        ex.shutdown();
        ex.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

        System.out
                .println("Without synchronization: " + runnableObject.counter);

        MyThread runnableSynchronizedObject = new MyThread();
        ExecutorService ex2 = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            ex2.execute(runnableSynchronizedObject);
        }

        ex2.shutdown();
        ex2.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        System.out.println("Without synchronization: "
                + runnableSynchronizedObject.counter);

    }
}

答案 3 :(得分:0)

mySampleExecutor.execute(mySampleThread);mySampleThread方法不会有任何差异返回一个新的Runnable object.每个帖子都有自己的Frames

相关问题